从 0.15 版本开始,a 学习到的特征的全局项权重TfidfVectorizer
可以通过属性访问idf_
,这将返回一个长度等于特征维度的数组。按此权重对特征进行排序以获得权重最高的特征:
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
lectures = ["this is some food", "this is some drink"]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(lectures)
indices = np.argsort(vectorizer.idf_)[::-1]
features = vectorizer.get_feature_names()
top_n = 2
top_features = [features[i] for i in indices[:top_n]]
print top_features
输出:
[u'food', u'drink']
通过 ngram 获取顶级特征的第二个问题可以使用相同的想法来完成,但需要一些额外的步骤将特征分成不同的组:
from sklearn.feature_extraction.text import TfidfVectorizer
from collections import defaultdict
lectures = ["this is some food", "this is some drink"]
vectorizer = TfidfVectorizer(ngram_range=(1,2))
X = vectorizer.fit_transform(lectures)
features_by_gram = defaultdict(list)
for f, w in zip(vectorizer.get_feature_names(), vectorizer.idf_):
features_by_gram[len(f.split(' '))].append((f, w))
top_n = 2
for gram, features in features_by_gram.iteritems():
top_features = sorted(features, key=lambda x: x[1], reverse=True)[:top_n]
top_features = [f[0] for f in top_features]
print '{}-gram top:'.format(gram), top_features
输出:
1-gram top: [u'drink', u'food']
2-gram top: [u'some drink', u'some food']