【发布时间】:2016-09-12 21:54:35
【问题描述】:
您好,我是 scikit 学习和数据科学的新手。我在尝试从矢量化器中检索信息最多的功能时遇到了上述问题。我的代码(经过编辑以反映@Gang 的评论):
values = dataset.data
word_vectorizer = CountVectorizer(analyzer='word', stop_words=custom_stop_words)
trainset = word_vectorizer.fit_transform(values)
tags = ['dem','rep','dem','rep']
tags = np.array(tags)
trainset = trainset.toarray()
word_svm = svm.LinearSVC()
word_svm.fit(trainset, tags)
def most_informative_feature_for_binary_classification(vectorizer, classifier, n=10):
class_labels = classifier.classes_
feature_names = vectorizer.get_feature_names()
topn_class1 = sorted(zip(classifier.coef_[0], feature_names))[:n]
topn_class2 = sorted(zip(classifier.coef_[0], feature_names))[-n:]
for coef, feat in topn_class1:
print class_labels[0], coef, feat
print
for coef, feat in reversed(topn_class2):
print class_labels[1], coef, feat
most_informative_feature_for_binary_classification(word_vectorizer, word_svm)
终端输出:
Traceback (most recent call last):
File "classification.py", line 251, in <module>
word_svm.fit(trainset, tags)
File "/usr/local/lib/python2.7/site-packages/sklearn/svm/classes.py", line 205, in fit
dtype=np.float64, order="C")
File "/usr/local/lib/python2.7/site-packages/sklearn/utils/validation.py", line 520, in check_X_y
check_consistent_length(X, y)
File "/usr/local/lib/python2.7/site-packages/sklearn/utils/validation.py", line 176, in check_consistent_length
"%s" % str(uniques))
ValueError: Found arrays with inconsistent numbers of samples: [ 4 16149]
对于此事,我将不胜感激。如果我没有提供足够的信息,请告诉我。提前感谢您的宝贵时间!
【问题讨论】:
-
fit 方法需要一个维度为 (n, f) 的 X 数组(此处为训练集),其中 f 是特征数(计数向量化器中的单词数),n 是文档数.这是一种监督方法,因此它还必须采用长度为 n(文档数量)的 y(此处的标签,也称为目标)向量。看起来正在发生的事情是计数矢量化器正在吐出 16,149 个文档(可能是单词数?),值中有多少个文档?
-
如果你期待 4,不妨试试
word_vectorizer.fit_transform([values])
标签: python scikit-learn classification data-science