我正在与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