【问题标题】:Naive Bayes Classifier using Sklearn.naive_bayes.Bernoulli; how to use model to predict?使用 Sklearn.naive_bayes.Bernoulli 的朴素贝叶斯分类器;如何使用模型进行预测?
【发布时间】:2018-07-30 00:17:13
【问题描述】:

我有一个包含如下训练数据集的文件:

sentence           F1 F2 F3 F4 F5 class
this is a dog      0  1  0  0  0  1   
i like cats        1  0  0  0  0  1 
go to the fridge   0  0  1  0  0  0
i drive a car      0  0  0  1  0  0
i dislike rabbits  0  0  0  0  1  1

我有一组句子。我想预测(在这个例子中,现实生活中的句子更长),每个句子中是否包含动物(类)。我为每个句子分配了特征 F1 = 句子中提到的猫,F2 = 句子中提到的狗,F3 = 句子中提到的冰箱,F4 = 句子中提到的汽车,F5 = 句子中提到的兔子,类是句中是否为动物)。

那么我有另一个包含句子列表的文件(测试数据集):

dolphins live in the sea
bears live in the woods
there is no milk left
where are the zebras

我想使用训练数据集(上面的特征矩阵)训练朴素贝叶斯分类器,然后使用在句子测试文件上制作的模型。我可以这样做吗?

我试过了:

import numpy as np
import sklearn.naive_bayes import BernoulliNB

sentence = []
feature1 = []
feature2 = []
feature3 = []
feature4 = []
feature5 = []
class_name = []

test_dataset = [line.strip() for line in open(sys.argv[2])]

for line in open(sys.argv[1]):
    line = line.strip().split('\t')
    sentence.append(line[0])
    feature1.append(line[1])
    feature2.append(line[2])
    feature3.append(line[3])
    feature4.append(line[4])
    feature5.append(line[5])
    class_name.append(line[6])

list_of_features = [feature1,feature2,feature3,feature4,feature5]

#I'm not sure if this is right: question 1 below
clf = BernoulliNB()
clf.fit(list_of_features,class_name)

# I'm not sure what goes in the next line: question 2 below
print clf.predict(??)

我有一些问题。

  1. 当我将代码运行到句子 clf.fit 时,我得到了错误:

    文件“naive_bayes.py”,第 28 行,在 clf.fit(list_of_features,class_name) 文件“/usr/local/lib/python2.7/dist-packages/sklearn/naive_bayes.py”,第 527 行,适合 X, y = check_X_y(X, y, 'csr') 文件“/usr/local/lib/python2.7/dist-packages/sklearn/utils/validation.py”,第 520 行,在 check_X_y check_consistent_length(X, y) 文件“/usr/local/lib/python2.7/dist-packages/sklearn/utils/validation.py”,第 176 行,在 check_consistent_length "%s" % str(唯一)) ValueError:发现样本数量不一致的数组:[5 10]

但是当我计算列表的长度时,它们的长度似乎都一样?谁能解释我在这里做错了什么?

  1. 我的第二个问题是,'print clf.predict()' 行读取 'print clf.predict(test_dataset)' 是否正确(即,我想要的句子列表,没有附加功能或类分配给 0 或 1 类;我现在无法测试这个,因为我似乎无法克服问题 1) 中的错误。

  2. 作为旁注,一旦我最终可以让它发挥作用,以某种方式计算出预测器的准确性会很棒。但是,我正在努力让基础知识先发挥作用。

编辑 1:修改后的脚本

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

sentence = []
feature1 = []
feature2 = []
feature3 = []
feature4 = []
feature5 = []
class_name = []

for line in open(sys.argv[1]):
    line = line.strip().split('\t')
    sentence.append(line[0])
    feature1.append(int(line[1]))
    feature2.append(int(line[2]))
    feature3.append(int(line[3]))
    feature4.append(int(line[4]))
    feature5.append(int(line[5]))
    class_name.append(int(line[6]))

print feature1
print feature2
print feature3
print feature4
print feature5
print class_name


list_of_features = [feature1,feature2,feature3,feature4,feature5]
transpos_list_of_features = np.array(list_of_features).T
clf = BernoulliNB()
print clf.fit(transpos_list_of_features,class_name)
#print clf.predict(??)

输出:

[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 1, 1, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1]
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1]
BernoulliNB(alpha=1.0, binarize=0.0, class_prior=None, fit_prior=True)

【问题讨论】:

    标签: python machine-learning scikit-learn naivebayes


    【解决方案1】:

    1- 这里有几个问题。

    • 首先,确保正确解析文件。如果您的火车文件与上述几行完全相同,那么您可能需要跳过第一行。它包含标题,不应在您的 X 或 Y 矩阵中。确保 feature 和 class_name 变量包含你想要的。您可以通过打印来检查它们。
    • sentence.append(line[0]) 我猜,你得到的是字符串 '0' 或 '1' 而不是整数值。我不认为这个 scikit 模块可以处理字符串值。您应该将它们转换为整数。可能类似于sentence.append(int(line[0]))
    • list_of_features 变量是 no_of_features x no_of_features 矩阵。它的形状应该是 n_samples x n_features。你可以通过list_of_features = np.array(list_of_features).T转置它

    2 - 分类器不知道如何将句子映射到特征,因此您必须明确给出特征。您可以通过遍历句子并检查目标词是否存在来实现。

    编辑:

    import numpy as np
    from sklearn.naive_bayes import BernoulliNB
    
    feature_word_list = ["cat", "dog", "fridge", "car", "rabbit"]
    feature1 = [0, 1, 0, 0, 0]
    feature2 = [1, 0, 0, 0, 0]
    feature3 = [0, 0, 1, 0, 0]
    feature4 = [0, 0, 0, 1, 0]
    feature5 = [1, 1, 0, 0, 1]
    class_name_list = [1, 1, 0, 0, 1]
    
    train_features = np.array([feature1,feature2,feature3,feature4,feature5]).T
    
    clf = BernoulliNB()
    clf.fit(train_features, class_name_list)
    

    上面的代码是一样的,只是我直接放了特征值而不从文件中读取。

    test_data = ["this is about dog and cats","not animal related sentence"]
    test_feature_list = []
    for test_instance in test_data:
      test_feature = [1 if feature_word in test_instance else 0 for feature_word in feature_word_list]
      test_feature_list.append(test_feature) 
    
    test_feature_matrix = np.array(test_feature_list)
    print(test_feature_matrix)
    

    现在您的 test_feature_matrix 将如下所示:

    [[1 1 0 0 0]
     [0 0 0 0 0]]
    

    请注意,我有 2 个测试数据,因此矩阵有 2 个对应的行,每列代表一个特征值(即句子中是否存在特定单词)。这就是我在第 2 点中试图说的,分类器不知道“猫”、“冰箱”或其他东西,但它需要的是单词是否存在,1 或 0。

    现在您可以预测这些测试数据(句子)的标签:

    predicted_label_list = clf.predict(test_feature_matrix)
    print(predicted_label_list)
    

    给出

    的结果
    [1 0]
    

    注意:它可能不适用于您的测试数据,因为它包含不在您的特征空间和训练数据中的单词。我的意思是您的测试数据包含“斑马”,但训练集中没有“斑马”,因此它可能归类为 0。

    【讨论】:

    • 谢谢。所以我在上面编辑了问题,显示了我正在使用的实际文件的实际输出(上面第 1 点的所有要点都已修复)。所以我想我不理解的部分是你的第 2 点。所以我现在已经建立了这个模型。我在一个文件中有一组新的句子。我只是不明白如何将两者结合起来?如果可能的话,您能否非常具体但基本地解释一下?或者,如果可能的话,您能否提供几行 python 代码来展示如何组合它们,以便我可以看到和理解(虽然我知道这更费力,所以如果不可能,请不要担心)。
    • @E.Dohrty 我更新了我的答案,你可以看看。
    猜你喜欢
    • 2016-08-16
    • 2013-12-02
    • 2013-06-21
    • 2019-01-22
    • 2016-07-29
    • 2012-03-29
    • 2017-05-19
    • 2017-04-19
    • 2017-01-10
    相关资源
    最近更新 更多