麻烦实施伯努利朴素贝叶斯分类器

时间:2018-01-01 19:24:22

标签: python scikit-learn text-classification naivebayes

我正在尝试从Bernoulli Naive Bayes库中实现scikit-learn分类器以进行文本分类。但我坚持这个错误

  

ValueError:预期的2D数组,改为获得1D数组:

     

如果数据具有单个要素,则使用array.reshape(-1,1)重新整形数据;如果包含单个样本,则使用array.reshape(1,-1)重新整形数据。

详细错误

Traceback (most recent call last):
  File "BNB.py", line 27, in <module>
    clf.fit(train_data, train_labels)
  File "/home/atinesh/.local/lib/python3.6/site-packages/sklearn/naive_bayes.py", line 579, in fit
    X, y = check_X_y(X, y, 'csr')
  File "/home/atinesh/.local/lib/python3.6/site-packages/sklearn/utils/validation.py", line 573, in check_X_y
    ensure_min_features, warn_on_dtype, estimator)
  File "/home/atinesh/.local/lib/python3.6/site-packages/sklearn/utils/validation.py", line 441, in check_array
    "if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:
array=['Apple' 'Banana' 'Cherry' 'Grape' 'Guava' 'Lemon' 'Mangos' 'Orange'
 'Strawberry' 'Watermelon' 'Potato' 'Spinach' 'Carrot' 'Onion' 'Cabbage'
 'Barccoli' 'Tomatoe' 'Pea' 'Cucumber' 'Eggplant'].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

&#34; BNB.py&#34;

from sklearn.naive_bayes import BernoulliNB

dataPos = ['Apple', 'Banana', 'Cherry', 'Grape', 'Guava', 'Lemon', 'Mangos',
            'Orange', 'Strawberry', 'Watermelon']

dataNeg = ['Potato', 'Spinach', 'Carrot', 'Onion', 'Cabbage', 'Barccoli', 
            'Tomatoe', 'Pea', 'Cucumber', 'Eggplant']

def get_data():
    examples = []
    labels   = []

    for item in dataPos:
        examples.append(item)
        labels.append('positive')

    for item in dataNeg:
        examples.append(item)
        labels.append('negative')

    return examples, labels

train_data, train_labels = get_data()

# Train
clf = BernoulliNB()
clf.fit(train_data, train_labels)

# Predict
print(clf.predict('Apple Banana'))
print(clf.predict_proba('Apple Banana'))

2 个答案:

答案 0 :(得分:3)

我建议在sklearn中使用LabelBinarizer

from sklearn.naive_bayes import BernoulliNB
import numpy as np
from sklearn import preprocessing

dataPos = ['Apple', 'Banana', 'Cherry', 'Grape', 'Guava', 'Lemon', 'Mangos',
                       'Orange', 'Strawberry', 'Watermelon']

dataNeg = ['Potato', 'Spinach', 'Carrot', 'Onion', 'Cabbage', 'Barccoli',
                       'Tomatoe', 'Pea', 'Cucumber', 'Eggplant']

Y=[0]*10+[1]*10
Y=np.array(Y)

lb = preprocessing.LabelBinarizer()
X = lb.fit_transform(dataPos+dataNeg)
clf = BernoulliNB()
clf.fit(X, Y)

test_sample = lb.transform([['Apple'],['Banana'],['Spinach']])
print clf.predict(test_sample)

您的代码错误,因为在执行clf.fit(X,Y)时,X需要是2d数组。每行对应一个特征向量。

答案 1 :(得分:0)

如果将简单的python列表传递给scikit_learn,它将被解释为shape(n,)数组。您可能想要做的是将示例和标签的列表转换为numpy数组,并将它们重新整形/调整为形状为(n,1)的线矢量。 例如:

import numpy as np

examples = np.array(['Apple', 'Banana', 'Cherry', 'Grape', 'Guava', 'Lemon', 'Mangos','Orange', 'Strawberry', 'Watermelon'])
examples.shape  # returns (10, ), a 1D-array
examples.resize((10,1))
examples.shape  # returns (10, 1), which is a 2-D array

或者对于更简单的解决方案,您可以简单地提供fit方法:

clf.fit([train_data], [train_labels])

但是,由于您已经有一个专门的方法来格式化数据,为什么不在那里使用numpy并返回具有正确尺寸的列表。

希望这有助于你的努力。