【发布时间】:2018-09-17 10:21:48
【问题描述】:
很抱歉,我仍然无法解决这个无问题。我正在使用 NMF 算法来获取语料库的主题,然后我尝试检索附加到每个主题的文档。但是没有人阻止我!当我尝试检索文档时,出现错误
脚本:
import pandas
import numpy as np
import pandas as pd
from sklearn.decomposition import NMF
from sklearn.feature_extraction.text import TfidfVectorizer
def display_topics(model, feature_names, n_top_words):
for topic_idx, topic in enumerate(model.components_):
print "Topic %d:" % (topic_idx)
print " ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]])
text = pandas.read_csv('pretraitement_virgile.csv', encoding = 'utf-8')
good_text = text['phrase']
bad_text = text['raw_phrase']
bad_text_list = bad_text.values.tolist()
good_text_list = good_text.values.tolist()
tfidf_vectorizer = TfidfVectorizer()
tfidf = tfidf_vectorizer.fit_transform(good_text_list)
tfidf_feature_names = tfidf_vectorizer.get_feature_names()
topics_number = 3
# Run NMF
nmf = NMF(n_components=topics_number, random_state=1, alpha=.1, l1_ratio=.5, init='nndsvd').fit(tfidf)
document_topics = nmf.fit_transform(tfidf)
n_top_words = 10
print 'NMF topics'
topics = display_topics(nmf, tfidf_feature_names, n_top_words)
print topics
print
print 'Documents per topic'
for topic in range(len(topics)):
if topic == None:
pass
else:
print("Topic {}:".format(topic))
docs = np.argsort(document_topics[:, topic])[::-1]
for mail in docs[:3]:
bad_text_list_n = " ".join(bad_text_list[mail].split(",")[:2])
print (" ".join(good_text_list[mail].split(",")[:2]) + ',' + bad_text_list_n)
我试图设置一个忽略名称的条件,但它不起作用。我仍然有同样的错误。
主题 0:
订单取消交货日期不希望商店总是提前
主题一:
产品没有破损,只有包裹到达收到颜色颜色交付
主题 2:
产品不退还网站商店收据可提前订购
无
与主题相关的文档
Traceback(最近一次调用最后一次): 文件“NMF.py”,第 49 行,在 对于范围内的主题(len(topics)):
TypeError: 'NoneType' 类型的对象没有 len()
我需要这个结果:
主题 0:
订单取消交货日期不希望商店总是提前
主题一:
产品没有破损,只有包裹到达收到颜色颜色交付
主题 2:
产品不退还网站商店收据可提前订购
与主题相关的文档
主题 0:
文字文字文字
文字文字文字
文字文字文字
主题一:
文字文字文字
文字文字文字
文字文字文字
主题 2:
文字文字文字
文字文字文字
文字文字文字
一些(愚蠢的)数据示例:
phrase,raw_phrase
delicious fruit mango, the mango is a delicious fruit
important object computer, the computer is an important object
popular banana fruit, banana is a popular fruit
pen important thing, pen is an important thing
purple grape, the grape is purple
phone world object, the phone is a worldwide object
【问题讨论】:
-
或许可以试试
for topic in topics:而不是for topic in range(len(topics)) -
能否也粘贴一些示例数据来重现错误?
-
@amanbirs 完成!
标签: python nonetype topic-modeling nmf