Python scikit-learn 预测失败

我是Python和机器学习的新手。我尝试实现一个简单的机器学习脚本来预测文本的主题,例如,关于巴拉克·奥巴马的文本应该被映射到政治家类别。

我认为我采取了正确的步骤来实现这一点,但我不完全确定,所以我来问问大家。

首先,这里是我的小脚本:

#importsfrom sklearn.datasets import fetch_20newsgroupsfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfTransformerfrom sklearn.naive_bayes import MultinomialNB#dictionary for mapping the targetscategories_dict = {'0' : 'politiker','1' : 'nonprofit org'}import glob#get filenames from docsfilepaths = glob.glob('Data/*.txt')print(filepaths)docs = []for path in filepaths:doc = open(path,'r')docs.append(doc.read())#print docscount_vect = CountVectorizer()#train DataX_train_count = count_vect.fit_transform(docs)#print X_train_count.shape#tfidf transformation (occurences to frequencys)tfdif_transform = TfidfTransformer()X_train_tfidf = tfdif_transform.fit_transform(X_train_count)#get the categories you want to predict in a set, these must be in the order the train        docs are!categories = ['0','0','0','1','1']clf = MultinomialNB().fit(X_train_tfidf,categories)#try to predictto_predict = ['Barack Obama is the President of the United States','Greenpeace']#transform(not fit_transform) the new data you want to predictX_pred_counts = count_vect.transform(to_predict)X_pred_tfidf = tfdif_transform.transform(X_pred_counts)print X_pred_tfidf#predictpredicted = clf.predict(X_pred_tfidf)for doc,category in zip(to_predict,predicted):    print('%r => %s' %(doc,categories_dict[category]))

我对使用这个所需的一般工作流程很确定,但我不确定如何将类别映射到我用来训练分类器的文档。我知道它们必须按正确的顺序排列,我认为我已经做到了这一点,但它没有输出正确的类别。

这是因为我用来训练分类器的文档质量不好,还是我犯了某个我不知道的错误?

他预测这两个新文本都是关于目标0(政治家)的

提前感谢。


回答:

看起来模型的超参数没有正确调整。数据量如此少的情况下很难得出结论,但如果你使用:

model = MultinomialNB(0.5).fit(X, y)# ormodel = LogisticRegression().fit(X, y)

你会得到预期的结果,至少对于像“Greenpeace”、“Obama”、“President”这样的词,它们与其相应的类别有明显的相关性。我快速查看了模型的系数,看起来它做的是正确的事情。

对于更复杂的主题建模方法,我建议你看看gensim

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中创建了一个多类分类项目。该项目可以对…

发表回复

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