Ank*_*nki 2 machine-learning scikit-learn
因此,我通过执行以下几行来创建CountVectorizer对象。
count_vectorizer = CountVectorizer(binary='true')
data = count_vectorizer.fit_transform(data)
Run Code Online (Sandbox Code Playgroud)
现在我有了一个新字符串,我想将此字符串映射到我从CountVectorizer获得的TDM矩阵。因此,我期望输入到TDM的字符串是一个对应的文档术语向量。
我试过了,
count_vectorizer.transform([string])
Run Code Online (Sandbox Code Playgroud)
给了一个错误,AttributeError:找不到转换添加一个堆栈跟踪的一部分,它是一个很长的堆栈跟踪,因此我只添加了相关的位,它们是跟踪的最后几行。
File "/Users/ankit/Desktop/geny/APIServer/RUNTIME/src/controller/sentiment/Sentiment.py", line 29, in computeSentiment
vec = self.models[model_name]["vectorizer"].transform([string])
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/sparse/base.py", line 440, in __getattr__
raise AttributeError(attr + " not found")
Run Code Online (Sandbox Code Playgroud)
请指教。
谢谢
安吉特S
您显示的示例不可复制-此处的字符串变量是什么?但是下面的代码似乎完美地工作:
from sklearn.feature_extraction.text import CountVectorizer
data = ["aa bb cc", "cc dd ee"]
count_vectorizer = CountVectorizer(binary='true')
data = count_vectorizer.fit_transform(data)
# Check if your vocabulary is being built perfectly
print count_vectorizer.vocabulary_
# Trying a couple new string with added new word. new word should be ignored
newData = count_vectorizer.transform(["aa dd mm", "aa bb"])
print newData
# You can get the array by writing
print newData.toarray()
Run Code Online (Sandbox Code Playgroud)

好吧,count_vectorizer.transform()接受字符串列表-而不是单个字符串。如果变换拟合不起作用,则应该引发“ ValueError:词汇表不正确或为空!” 如果发生此类错误,请粘贴整个回溯堆栈(异常堆栈)。没有人可以看到AttributeError的来源-您的代码或sklearn中的一些内部错误。