Naivebayes MultinomialNB scikit-learn/sklearn

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

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

编辑 数据示例

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

根据这个指令,我创建了一个新的列,如果评分大于3,则评论为正面,否则为负面

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

回答:

MultinomialNBfit方法需要输入xy。其中,x应该是训练向量(训练数据),而y应该是目标值。

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

更详细的说明:

X : {array-like, sparse matrix}, shape = [n_samples, n_features]训练向量,其中n_samples是样本数量,n_features是特征数量。y : array-like, shape = [n_samples]目标值。

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


玩具示例:

from sklearn.datasets import fetch_20newsgroupsfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.naive_bayes import MultinomialNBfrom sklearn import metricsnewsgroups_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()# 以下将是训练数据vectors = vectorizer.fit_transform(newsgroups_train.data)vectors.shapenewsgroups_test = fetch_20newsgroups(subset='test',                                     categories=categories)# 这是测试数据vectors_test = vectorizer.transform(newsgroups_test.data)clf = MultinomialNB(alpha=.01)# 使用训练数据进行拟合# 在拟合前检查形状vectors.shape#(2034, 34118)newsgroups_train.target.shape#(2034,)# 使用训练数据拟合模型clf.fit(vectors, newsgroups_train.target)# 使用测试数据进行预测pred = clf.predict(vectors_test)

编辑:

newsgroups_train.target只是一个包含标签(或目标或类别)numpy数组。

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

需要这个变量来拟合分类器。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注