2016-09-22 54 views
0

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

任何人都知道如何应对这种结构/异常? 在此先感谢您的帮助。

+1

'“A”:[[10,15,12,14],[20,30,10,43]]','np.array(df.A)。重塑(1,4)':将2x4矩阵重塑为1x4? – Jeon

+0

原本每行不包含矢量:第一行为[10,15,12,14],第二行为[20,30,10,43]。如果我留下标量的原始语法,则会出现相同的异常。 – LeoCella

+0

检查'np.array(df.A).shape',它返回(1,)为单行,(2,)为两行。它不返回一种(1,8)或(2,4) – Jeon

回答

1

有你的X仔细看看:

>>> X 
array([[[10, 15, 12, 14], [20, 30, 10, 43]], 
     [2, 2], 
     [2, 2]], dtype=object) 
>>> type(X[0,0]) 
<class 'list'> 

请注意,这是dtype=object,以及这些对象之一是list,因此“设置数组元素与序列的部分问题是,np.array(df.A)没有。正确地创建一个二维数组:

>>> np.array(df.A) 
array([[10, 15, 12, 14], [20, 30, 10, 43]], dtype=object) 
>>> _.shape 
(2,) # oops! 

但是用np.stack(df.A)修复问题

您是否在寻找:

>>> X = np.concatenate([ 
     np.stack(df.A),     # condense A to (N, 4) 
     np.expand_dims(df.C, axis=-1), # expand C to (N, 1) 
     np.expand_dims(df.R, axis=-1), # expand R to (N, 1) 
     axis=-1 
    ) 
>>> X 
array([[10, 15, 12, 14, 2, 2], 
     [20, 30, 10, 43, 2, 2]], dtype=int64) 
+0

我刚刚尝试类似的玩具示例与分层pca(从[[],.. []]到[...])的拟合,并且工作。 现在我会尝试将熊猫数据框转换为合适的numpy矩阵。非常感谢你的帮助!!!! – LeoCella

+0

我必须指出,这个代码的正确版本应该是: X = np.concatenate([np.stack(df.flat_pca,axis = 0),[df.C1,df.C2]] ,axis = 0).transpose();否则C1和C2将被读取,比如按列而不是按行读取。 – LeoCella

+0

这对我来说不起作用。查看我的更新 – Eric

1

为大熊猫据帧转换为NumPy的的矩阵,

import pandas as pd 

def df2mat(df): 
    a = df.as_matrix() 
    n = a.shape[0] 
    m = len(a[0]) 
    b = np.zeros((n,m)) 
    for i in range(n): 
     for j in range(m): 
      b[i,j]=a[i][j] 
return b 

df = pd.DataFrame({"A":[[1,2],[3,4]]}) 
b = df2mat(df.A) 

此后,串联。

+0

我正在将您的整个数据框翻译成一个numpy结构。我还没有完成,因此目前我无法给你一个反馈。我会尽快做! 但是,感谢您的帮助! – LeoCella

相关问题