4

我正在尝试使用 scikit 使用余弦相似度来查找类似的问题。我正在尝试互联网上提供的此示例代码。链路 1链路 2

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from nltk.corpus import stopwords
import numpy as np
import numpy.linalg as LA

train_set = ["The sky is blue.", "The sun is bright."]
test_set = ["The sun in the sky is bright."]
stopWords = stopwords.words('english')

vectorizer = CountVectorizer(stop_words = stopWords)
transformer = TfidfTransformer()

trainVectorizerArray = vectorizer.fit_transform(train_set).toarray()
trainVectorizerArray = vectorizer.
testVectorizerArray = vectorizer.transform(test_set).toarray()
print 'Fit Vectorizer to train set', trainVectorizerArray
print 'Transform Vectorizer to test set', testVectorizerArray
cx = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)

for vector in trainVectorizerArray:
    print vector
    for testV in testVectorizerArray:
        print testV
        cosine = cx(vector, testV)
        print cosine

transformer.fit(trainVectorizerArray)
print transformer.transform(trainVectorizerArray).toarray()

transformer.fit(testVectorizerArray)
tfidf = transformer.transform(testVectorizerArray)
print tfidf.todense()

我总是收到这个错误

Traceback (most recent call last):
File "C:\Users\Animesh\Desktop\NLP\ngrams2.py", line 14, in <module>
trainVectorizerArray = vectorizer.fit_transform(train_set).toarray()
File "C:\Python27\lib\site-packages\scikit_learn-0.13.1-py2.7-win32.egg\sklearn  \feature_extraction\text.py", line 740, in fit_transform
raise ValueError("empty vocabulary; training set may have"
ValueError: empty vocabulary; training set may have contained only stop words or min_df  (resp. max_df) may be too high (resp. too low).

我什至检查了此链接上可用的代码。我得到了错误AttributeError: 'CountVectorizer' object has no attribute 'vocabulary'

如何解决这个问题?

我在 Windows 7 32 位和 scikit_learn 0.13.1 上使用 Python 2.7.3。

4

1 回答 1

6

由于我正在运行开发(0.14 之前)版本,feature_extraction.text模块进行了大修,所以我没有收到相同的错误消息。但我怀疑您可以通过以下方式解决此问题:

vectorizer = CountVectorizer(stop_words=stopWords, min_df=1)

min_df参数导致CountVectorizer丢弃出现在太少文档中的任何术语(因为它没有任何预测价值)。默认情况下,它设置为 2,这意味着您的所有术语都会被丢弃,因此您会得到一个空的词汇表。

于 2013-03-05T10:11:02.510 回答