我正在與scikit模型的擬合(即一個ExtraTreesRegressor)與補充的監督功能的選擇的目的。值錯誤:設置一個數組元素與序列
我做了一個玩具比如爲了像最清晰越好。這就是玩具代碼:
import pandas as pd
import numpy as np
from sklearn.ensemble import ExtraTreesRegressor
from itertools import chain
# Original Dataframe
df = pd.DataFrame({"A": [[10,15,12,14],[20,30,10,43]], "R":[2,2] ,"C":[2,2] , "CLASS":[1,0]})
X = np.array([np.array(df.A).reshape(1,4) , df.C , df.R])
Y = np.array(df.CLASS)
# prints
X = np.array([np.array(df.A), df.C , df.R])
Y = np.array(df.CLASS)
print("X",X)
print("Y",Y)
print(df)
df['A'].apply(lambda x: print("ORIGINAL SHAPE",np.array(x).shape,"field:",x))
df['A'] = df['A'].apply(lambda x: np.array(x).reshape(4,1),"field:",x)
df['A'].apply(lambda x: print("RESHAPED SHAPE",np.array(x).shape,"field:",x))
model = ExtraTreesRegressor()
model.fit(X,Y)
model.feature_importances_
X [[[10, 15, 12, 14] [20, 30, 10, 43]]
[2 2]
[2 2]]
Y [1 0]
A C CLASS R
0 [10, 15, 12, 14] 2 1 2
1 [20, 30, 10, 43] 2 0 2
ORIGINAL SHAPE (4,) field: [10, 15, 12, 14]
ORIGINAL SHAPE (4,) field: [20, 30, 10, 43]
---------------------------
這就是出現異常:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-37-5a36c4c17ea0> in <module>()
7 print(df)
8 model = ExtraTreesRegressor()
----> 9 model.fit(X,Y)
/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/ensemble/forest.py in fit(self, X, y, sample_weight)
210 """
211 # Validate or convert input data
--> 212 X = check_array(X, dtype=DTYPE, accept_sparse="csc")
213 if issparse(X):
214 # Pre-sort indices to avoid that each individual tree of the
/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
371 force_all_finite)
372 else:
--> 373 array = np.array(array, dtype=dtype, order=order, copy=copy)
374
375 if ensure_2d:
ValueError: setting an array element with a sequence.
我注意到,涉及np.arrays。所以我試圖去適應另一個玩具數據框,這是最基本的一個,只有標量,並沒有出現錯誤。我試圖保留相同的代碼,並通過添加另一個包含單維數組的字段來修改相同的玩具數據框,現在出現了相同的異常。
我環顧四周,但到目前爲止,我還沒有甚至試圖讓一些整形找到了解決方案,轉換成列表,np.array等和矩陣式在我的真正的問題。現在我正在沿着這個方向努力。
我也看到了,通常當有withdifferent長度betweeen樣本,但不是玩具例子的情況下,陣列這類問題arised。
任何人都知道如何應對這種結構/異常? 在此先感謝您的幫助。
'「A」:[[10,15,12,14],[20,30,10,43]]','np.array(df.A)。重塑(1,4)':將2x4矩陣重塑爲1x4? – Jeon
原本每行不包含矢量:第一行爲[10,15,12,14],第二行爲[20,30,10,43]。如果我留下標量的原始語法,則會出現相同的異常。 – LeoCella
檢查'np.array(df.A).shape',它返回(1,)爲單行,(2,)爲兩行。它不返回一種(1,8)或(2,4) – Jeon