【问题标题】:ValueError when using Multinomial Naive Bayes classifier使用多项朴素贝叶斯分类器时的 ValueError
【发布时间】:2016-05-08 00:04:30
【问题描述】:

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

数据集是分类的,每个特征都有超过 2 个可能的属性,所以我使用多项式 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])

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    简而言之,不,它不应该能够将字符串作为输入。您必须进行一些预处理,但幸运的是 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 只会转换已训练过的字符串,因此请确保正确预处理数据。

    【讨论】:

    • 谢谢,我试试看!
    • 您不应该使用OrdinalEncoder 来转换功能吗?来自文档:“这个转换器应该用于编码目标值,即y,而不是输入X。”
    猜你喜欢
    • 2012-02-11
    • 2020-04-22
    • 2017-01-10
    • 2017-09-14
    • 2014-07-12
    • 2020-06-02
    • 2013-12-02
    • 2018-05-09
    相关资源
    最近更新 更多