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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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