首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python学习预测失败

Python学习预测失败
EN

Stack Overflow用户
提问于 2015-01-13 14:22:50
回答 1查看 141关注 0票数 1

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

我想我做了正确的举动,但我不能百分之百肯定,所以我问你们。

首先是我的小剧本:

代码语言:javascript
复制
#imports
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
#dictionary for mapping the targets
categories_dict = {'0' : 'politiker','1' : 'nonprofit org'}

import glob
#get filenames from docs
filepaths = glob.glob('Data/*.txt')
print(filepaths)

docs = []

for path in filepaths:
doc = open(path,'r')
docs.append(doc.read())
#print docs


count_vect = CountVectorizer()
#train Data
X_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 predict
to_predict = ['Barack Obama is the President of the United States','Greenpeace']

#transform(not fit_transform) the new data you want to predict
X_pred_counts = count_vect.transform(to_predict)
X_pred_tfidf = tfdif_transform.transform(X_pred_counts)
print X_pred_tfidf

#predict
predicted = clf.predict(X_pred_tfidf)

for doc,category in zip(to_predict,predicted):
    print('%r => %s' %(doc,categories_dict[category]))

我确信使用这个工具所需的一般工作流,但我不确定如何将这些类别映射到我用来训练分类器的文档中。我知道他们必须在正确的顺序,我想我得到了,但它没有输出正确的类别。

是因为我用来训练分类器的文件不好,还是我犯了一个我不知道的错误?

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

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-13 14:59:44

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

代码语言:javascript
复制
model = MultinomialNB(0.5).fit(X, y)
# or
model = LogisticRegression().fit(X, y)

你会得到预期的结果,至少是像“绿色和平”、“奥巴马”、“总统”这样的词,这些词显然与其相应的类别相关。我快速地看了一下模型的系数,它似乎在做正确的事情。

对于更复杂的主题建模方法,我建议您查看一下gensim

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27924292

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档