首页 > 解决方案 > Naivebayes MultinomialNB scikit-learn/sklearn

问题描述

我正在构建一个朴素贝叶斯分类器,并按照 scikit-learn 网站上的教程进行操作。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
import csv
import string
from sklearn.cross_validation import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB

# Importing dataset
data = pd.read_csv("test.csv", quotechar='"', delimiter=',',quoting=csv.QUOTE_ALL, skipinitialspace=True,error_bad_lines=False)
df2 = data.set_index("name", drop = False)



df2['sentiment'] = df2['rating'].apply(lambda rating : +1 if rating > 3 else -1)


train, test = train_test_split(df2, test_size=0.2)


count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(traintrain['review'])
test_matrix = count_vect.transform(testrain['review'])

clf = MultinomialNB().fit(X_train_tfidf, train['sentiment'])

第一个参数是词汇字典,它返回一个 Document-Term 矩阵。第二个参数应该是什么,twenty_train.target?

编辑数据示例

Name, review,rating
film1,......,1
film2, the film is....,5 
film3, film about..., 4

使用此说明,我创建了一个新列,如果评分>3,则评论为正面,否则为负面

df2['sentiment'] = df2['rating'].apply(lambda rating : +1 if rating > 3 else -1)

标签: pythonpython-3.xpandasmachine-learningscikit-learn

解决方案


期望作为输入的fit方法and 。现在,应该是训练向量(训练数据)并且应该是目标值。MultinomialNBxyxy

clf = MultinomialNB().fit(X_train_tfidf, twenty_train.target)

更详细地说:

X : {array-like, sparse matrix}, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and n_features is 
the number of features.

y : array-like, shape = [n_samples]
Target values.

注意:确保正确定义shape = [n_samples, n_features]and shape = [n_samples]ofx和。y否则,fit将抛出错误。


玩具示例:

from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics

newsgroups_train = fetch_20newsgroups(subset='train')
categories = ['alt.atheism', 'talk.religion.misc',
              'comp.graphics', 'sci.space']

newsgroups_train = fetch_20newsgroups(subset='train',
                                      categories=categories)
vectorizer = TfidfVectorizer()
# the following will be the training data
vectors = vectorizer.fit_transform(newsgroups_train.data)
vectors.shape

newsgroups_test = fetch_20newsgroups(subset='test',
                                     categories=categories)
# this is the test data
vectors_test = vectorizer.transform(newsgroups_test.data)

clf = MultinomialNB(alpha=.01)

# the fitting is done using the TRAINING data
# Check the shapes before fitting
vectors.shape
#(2034, 34118)
newsgroups_train.target.shape
#(2034,)

# fit the model using the TRAINING data
clf.fit(vectors, newsgroups_train.target)

# the PREDICTION is done using the TEST data
pred = clf.predict(vectors_test)

编辑:

newsgroups_train.target只是一个numpy包含.labels (or targets or classes)

import numpy as np

newsgroups_train.target
array([1, 3, 2, ..., 1, 0, 1])

np.unique(newsgroups_train.target)
array([0, 1, 2, 3])

所以在这个例子中,我们有 4 个不同的类/目标。

为了适合分类器,需要此变量。


推荐阅读