python - 使用多项式朴素贝叶斯分类器时出现 ValueError

标签 python machine-learning scikit-learn

这是我第一次使用 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/

相关文章:

python - glob.iglob 在所有子目录中查找所有 .txt 文件会产生错误

python - 使用 Py2exe 拒绝访问

python - 在列表中查找部分字典元素的索引

python - 在keras中使用predict_generator()时如何获取关联的图像名称

python - python如何合并集合列表并将它们作为集合返回?

python - 神经网络用一个神经元预测不良

machine-learning - 可用的无监督分类方法

python - 使用管道时 MSE 较差

python - SVM scikit learn 的归一化或标准化数据输入

python - 如何在不为每个类别构建分类器的情况下获得所有类别的预测概率?