Bal*_*rol 2 python text-processing machine-learning scikit-learn
我正在使用scikit-learn从一个"文字袋"文本中提取文本特征(文本在单个单词上标记).为此,我使用TfidfVectorizer来减轻非常频繁的单词的重量(即:"a","the"等).
text = 'Some text, with a lot of words...'
tfidf_vectorizer = TfidfVectorizer(
min_df=1, # min count for relevant vocabulary
max_features=4000, # maximum number of features
strip_accents='unicode', # replace all accented unicode char
# by their corresponding ASCII char
analyzer='word', # features made of words
token_pattern=r'\w{4,}', # tokenize only words of 4+ chars
ngram_range=(1, 1), # features made of a single tokens
use_idf=True, # enable inverse-document-frequency reweighting
smooth_idf=True, # prevents zero division for unseen words
sublinear_tf=False)
# vectorize and re-weight
desc_vect = tfidf_vectorizer.fit_transform([text])
Run Code Online (Sandbox Code Playgroud)
我现在希望能够将每个预测的特征与其相应的tfidf浮点值链接,并将其存储在字典中
{'feature1:' tfidf1, 'feature2': tfidf2, ...}
Run Code Online (Sandbox Code Playgroud)
我通过使用实现了它
d = dict(zip(tfidf_vectorizer.get_feature_names(), desc_vect.data))
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更好的,scikit-learn本地方式来做这样的事情.
非常感谢你.
对于单个文档,这应该没问题.另一种在文档集很小的情况下工作的替代方法是我使用Pandas的这个方法.
如果要对多个文档执行此操作,则可以调整代码DictVectorizer.inverse_transform:
desc_vect = desc_vect.tocsr()
n_docs = desc_vect.shape[0]
tfidftables = [{} for _ in xrange(n_docs)]
terms = tfidf_vectorizer.get_feature_names()
for i, j in zip(*desc_vect.nonzero()):
tfidftables[i][terms[j]] = X[i, j]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4561 次 |
| 最近记录: |