2015-05-21 164 views
19

由於是一個簡單的CSV文件:RandomForestClassfier.fit():ValueError異常:無法將字符串轉換爲浮動

A,B,C 
Hello,Hi,0 
Hola,Bueno,1 

顯然,真正的數據集比這要複雜得多,但是這一次重現錯誤。我試圖建立一個隨機森林分類吧,像這樣:

cols = ['A','B','C'] 
col_types = {'A': str, 'B': str, 'C': int} 
test = pd.read_csv('test.csv', dtype=col_types) 

train_y = test['C'] == 1 
train_x = test[cols] 

clf_rf = RandomForestClassifier(n_estimators=50) 
clf_rf.fit(train_x, train_y) 

但是調用,當我剛剛得到這個回溯擬合():

ValueError: could not convert string to float: 'Bueno' 

scikit學習的版本是0.16.1 。

回答

25

你必須在使用fit之前進行一些編碼。正如它被告知fit()不接受字符串,但你解決這個問題。

有可以使用幾類:

就個人而言,我前段時間在StackOverflow上發佈了幾乎the same question。我想有一個可擴展的解決方案,但沒有得到任何答案。我選擇了將所有字符串二進制化的OneHotEncoder。這是非常有效的,但如果你有很多不同的字符串矩陣將增長得非常快,並且需要記憶。

+0

謝謝。我最終找到了一個使用DictVectorizer的解決方案。我很驚訝沒有更好的文件來處理這樣的問題。如果我在這裏有足夠的業力,我會高興。 – nilkn

7

您無法將str傳遞給您的模型fit()方法。因爲它提到here

The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.

嘗試將您的數據浮動,給一個嘗試LabelEncoder

+0

咦,怎麼啦,有實例,明確使用字符串數據?我猜他們已經過時了嗎? – nilkn

+0

例如:http://nbviewer.ipython.org/github/ofermend/IPython-notebooks/blob/master/blog-part-1.ipynb – nilkn

+1

那麼處理這個問題的規範方法是什麼?我無法成爲第一個嘗試用scikit-learn做到這一點的人。 – nilkn

7

LabelEncoding工作對我來說(基本上你已經來編碼數據功能明智) (MYDATA是字符串數據類型的二維數組):

myData=np.genfromtxt(filecsv, delimiter=",", dtype ="|a20" ,skip_header=1); 

from sklearn import preprocessing 
le = preprocessing.LabelEncoder() 
for i in range(*NUMBER OF FEATURES*): 
    myData[:,i] = le.fit_transform(myData[:,i]) 
1

我也有類似的問題,並發現pandas.get_dummies()解決問題。具體而言,它將分類數據列分成布爾列集,每個輸入列中的每個唯一值都有一個新列。在你的情況,你將取代train_x = test[cols]有:

train_x = pandas.get_dummies(test[cols]) 

這些將train_x數據框爲以下形式,RandomForestClassifier可以接受:

C A_Hello A_Hola B_Bueno B_Hi 
0 0  1  0  0  1 
1 1  0  1  1  0 
相關問題