这是我第一次使用 Scikit,如果问题很愚蠢,我深表歉意。我正在尝试在 UCI 的蘑菇数据集上实现朴素贝叶斯分类器,以根据我自己从头开始编码的 NB 分类器测试结果。
数据集是分类的,每个特征都有超过 2 个可能的属性,因此我使用多项式 NB 而不是高斯或伯努利 NB。
但是,我不断收到以下错误 ValueError: Could not conversion 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
对此也非常有用。
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
只会转换经过训练的字符串,因此请确保正确预处理数据。
关于python - 使用多项式朴素贝叶斯分类器时出现 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35098326/