使用Multinomial Naive Bayes分类器时的ValueError

时间:2016-01-30 05:24:13

标签: python machine-learning scikit-learn

这是我第一次使用Scikit,如果问题很愚蠢,我会道歉。我正在尝试在UCI的蘑菇数据集上实现一个朴素的贝叶斯分类器来测试我自己从头开始编码的NB分类器的结果。

数据集是分类的,每个特征都有两个以上的可能属性,因此我使用了多项式NB而不是高斯或伯努利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])

1 个答案:

答案 0 :(得分:2)

简而言之,不应该将字符串作为输入。你将不得不做一些预处理,但幸运的是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

请记住: var row = $("tr#table_body_row"); var tbody = $("tbody#table_body"); for (i = 0; i < 12; i++) { tbody.append(row); } 只会转换已经过培训的字符串,因此请确保正确预处理数据。

相关问题