【问题标题】:How to implement Naive Bayes algorithm using "onehot_enc"?如何使用“onehot_enc”实现朴素贝叶斯算法?
【发布时间】:2019-02-15 15:41:54
【问题描述】:

我已按照site 对我的数据集使用朴素贝叶斯算法。这里数据集分为两个文件,一个是review.txt,另一个是label.txt。我在这里使用了“train_test_split”函数。

我的代码:

from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import BernoulliNB
from sklearn.metrics import confusion_matrix

with open("/Users/abc/review.txt") as f:
    reviews = f.read().split("\n")
with open("/Users/abc/label.txt") as f:
    labels = f.read().split("\n")

reviews_tokens = [review.split() for review in reviews]

onehot_enc = MultiLabelBinarizer()
onehot_enc.fit(reviews_tokens)


X_train, X_test, y_train, y_test = train_test_split(reviews_tokens, labels, test_size=0.20, random_state=1)


bnbc = BernoulliNB(binarize=None)
bnbc.fit(onehot_enc.transform(X_train), y_train)

score = bnbc.score(onehot_enc.transform(X_test), y_test)
print("score of Naive Bayes algo is :" , score)

predicted_y = bnbc.predict(onehot_enc.transform(X_test))
tn, fp, fn, tp = confusion_matrix(y_test, predicted_y).ravel()
precision_score = tp / (tp + fp)
recall_score = tp / (tp + fn)

print("precision_score :" , precision_score)
print("recall_score :" , recall_score)

但是,现在我的要求是将数据集放在单个文件(评论,标签)中。而且我需要单独手动提供测试和训练数据。因此,相应地实现了代码。

但是,我不能在这里使用“onehot_enc”。它会抛出错误,因为从“load_data”函数返回的评论是单词列表。

谁能建议我如何使用“onehot_enc”为我的数据集实现我的代码...

因此,为此我使用了以下代码:

train_data.csv:

review,label
Colors & clarity is superb,positive
Sadly the picture is not nearly as clear or bright as my 40 inch Samsung,negative

test_data.csv:

review,label
The picture is clear and beautiful,positive
Picture is not clear,negative

新代码:(在单个 csv 文件中提供评论、标签)

from sklearn.metrics import confusion_matrix
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score


def load_data(filename):
    reviews = list()
    labels = list()
    with open(filename) as file:
        file.readline()
        for line in file:
            line = line.strip().split(',')
            labels.append(line[1])
            reviews.append(line[0])

    return reviews, labels

X_train, y_train = load_data('/Users/abc/train_data.csv')
X_test, y_test = load_data('/Users/abc/test_data.csv')

【问题讨论】:

  • this 的可能重复项。两个 csv 文件的 sn-ps 相同,问题描述也非常相似。

标签: python machine-learning scikit-learn


【解决方案1】:

如果我理解正确,您想要的是将您的评论标记化以使用朴素贝叶斯。 一种热编码用于标签或分类数据。

您应该在标签上使用 0 和 1 而不是正面和负面,但不要在评论中使用它

对于您的文本,sklearn 中内置了用于标记化的函数,通常CountVectorizer 可能会在这里工作。

我建议查看follwing link,它详细解释了如何处理文本。

【讨论】:

  • 但是,在我提到的网站中,他们在 review_tokens 上使用了 One hot encoding。使用一种热编码,我得到了 90% 的准确率,使用 CountVectorizer,我得到了 49% 的准确率。
猜你喜欢
  • 2021-04-09
  • 2012-04-09
  • 1970-01-01
  • 2015-09-16
  • 2018-02-14
  • 2019-05-24
  • 2018-12-07
  • 1970-01-01
  • 2021-07-24
相关资源
最近更新 更多