我在下面的例子中Scikit学习文档,其中CountVectorizer的一些数据集使用.
问题:count_vect.vocabulary_.viewitems()列出所有条款及其频率.你如何根据出现次数对它们进行排序?
sorted( count_vect.vocabulary_.viewitems() ) 似乎不起作用.
我正在从电子邮件文本列表(以 csv 格式存储)中对垃圾邮件进行分类,但在此之前,我想从输出中获取一些简单的计数统计信息。我使用 sklearn 的 CountVectorizer 作为第一步,并通过以下代码实现
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
#import data from csv
spam = pd.read_csv('spam.csv')
spam['Spam'] = np.where(spam['Spam']=='spam',1,0)
#split data
X_train, X_test, y_train, y_test = train_test_split(spam_data['text'], spam_data['target'], random_state=0)
#convert 'features' to numeric and then to matrix or list
cv = CountVectorizer()
x_traincv = cv.fit_transform(X_train)
a = x_traincv.toarray()
a_list = cv.inverse_transform(a)
Run Code Online (Sandbox Code Playgroud)
输出以矩阵(名为“a”)或数组列表(名为“a_list”)格式存储,如下所示
[array(['do', 'I', 'off', 'text', 'where', 'you'],
dtype='<U32'),
array(['ages', 'will', 'did', 'driving', 'have', 'hello', 'hi', …Run Code Online (Sandbox Code Playgroud)