【发布时间】:2018-01-07 15:15:04
【问题描述】:
我想防止某些短语潜入我的模型。例如,我想阻止“红玫瑰”进入我的分析。我了解如何添加 Adding words to scikit-learn's CountVectorizer's stop list 中给出的个别停用词:
from sklearn.feature_extraction import text
additional_stop_words=['red','roses']
但是,这也会导致无法检测到其他 ngram,例如“red tulips”或“blue roses”。
我正在构建一个 TfidfVectorizer 作为我的模型的一部分,我意识到我需要的处理可能必须在此阶段之后进入,但我不知道如何执行此操作。
我的最终目标是对一段文本进行主题建模。这是我正在处理的一段代码(几乎直接从 https://de.dariah.eu/tatom/topic_model_python.html#index-0 借来的):
from sklearn import decomposition
from sklearn.feature_extraction import text
additional_stop_words = ['red', 'roses']
sw = text.ENGLISH_STOP_WORDS.union(additional_stop_words)
mod_vectorizer = text.TfidfVectorizer(
ngram_range=(2,3),
stop_words=sw,
norm='l2',
min_df=5
)
dtm = mod_vectorizer.fit_transform(df[col]).toarray()
vocab = np.array(mod_vectorizer.get_feature_names())
num_topics = 5
num_top_words = 5
m_clf = decomposition.LatentDirichletAllocation(
n_topics=num_topics,
random_state=1
)
doctopic = m_clf.fit_transform(dtm)
topic_words = []
for topic in m_clf.components_:
word_idx = np.argsort(topic)[::-1][0:num_top_words]
topic_words.append([vocab[i] for i in word_idx])
doctopic = doctopic / np.sum(doctopic, axis=1, keepdims=True)
for t in range(len(topic_words)):
print("Topic {}: {}".format(t, ','.join(topic_words[t][:5])))
编辑
示例数据框(我尝试插入尽可能多的边缘情况),df:
Content
0 I like red roses as much as I like blue tulips.
1 It would be quite unusual to see red tulips, but not RED ROSES
2 It is almost impossible to find blue roses
3 I like most red flowers, but roses are my favorite.
4 Could you buy me some red roses?
5 John loves the color red. Roses are Mary's favorite flowers.
【问题讨论】:
标签: python pandas scikit-learn nlp