2016-09-22 50 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

相關問題