簡體   English   中英

使用多項式朴素貝葉斯分類器時發生ValueError

[英]ValueError when using Multinomial Naive Bayes classifier

這是我第一次使用Scikit,如果問題很愚蠢,我深表歉意。 我正在嘗試在UCI的蘑菇數據集上實現朴素的貝葉斯分類器,以針對從頭開始編碼的我自己的NB分類器測試結果。

數據集是分類的,每個要素都有兩個以上的可能屬性,因此我使用了多項式NB而不是高斯或Bernouilli NB。

但是,我不斷收到以下錯誤ValueError: could not convert string to float: 'l' ,並且不確定該怎么做。 多項式NB是否應該能夠獲取字符串數據?

Example line of data - 0th column is the class (p for poisonous and e for edible) and the remaining 22 columns are the features.
p,x,s,n,t,p,f,c,n,k,e,e,s,s,w,w,p,w,o,p,k,s,u

# based off UCI's mushroom dataset http://archive.ics.uci.edu/ml/datasets/Mushroom

df = pd.DataFrame(data)
msk = np.random.rand(df.shape[0]) <= training_percent
train = data[msk]
test =  data[~msk] 

clf = MultinomialNB()
clf.fit(train.iloc[:, 1:], train.iloc[:, 0])

簡而言之,不應該不能將字符串作為輸入。 您將必須進行一些預處理,但是幸運的是, sklearn確實sklearn也有好處。

from sklearn import preprocessing
enc = preprocessing.LabelEncoder()
mushrooms = ['p','x','s','n','t','p','f','c','n','k','e','e','s','s','w','w','p','w','o']
enc.fit(mushrooms)
classes = enc.transform(mushrooms)
print classes
print enc.inverse_transform(classes)

哪個輸出

[ 6 10  7  4  8  6  2  0  4  3  1  1  7  7  9  9  6  9  5]
['p' 'x' 's' 'n' 't' 'p' 'f' 'c' 'n' 'k' 'e' 'e' 's' 's' 'w' 'w' 'p' 'w''o']

然后訓練轉換后的數據

clf.fit(enc.tranform(train.iloc[:, 1:], train.iloc[:, 0]))

切記: LabelEncoder僅會轉換經過訓練的字符串,因此請確保正確預處理數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM