gpt4 book ai didi

python - 使用 scikit-learn 时出现属性错误

转载 作者:太空狗 更新时间:2023-10-30 02:33:02 27 4
gpt4 key购买 nike

我正在尝试使用余弦相似度使用 scikit 查找类似问题。我正在尝试 Internet 上提供的示例代码。 Link1Link2

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).

我什至检查了 this link 上可用的代码.我收到错误 AttributeError: 'CountVectorizer' object has no attribute 'vocabulary'

如何解决这个问题?

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

最佳答案

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

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

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

关于python - 使用 scikit-learn 时出现属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15220961/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com