python - 为什么我在 python 上得到一个 list object is not callable 错误?
问题描述
我正在研究这个数据集 [ https://archive.ics.uci.edu/ml/datasets/Reuter_50_50]并尝试分析文本特征。
我读取文件并将其存储在文档变量中,如下所示:
documents=author_labels(raw_data_dir)
documents.to_csv(documents_filename,index_label="document_id")
documents=pd.read_csv(documents_filename,index_col="document_id")
documents.head()
随后,我尝试使用次线性增长生成 tf-idf 向量,并将其存储在一个名为 vectorizer 的变量中。
vectorizer = TfidfVectorizer(input="filename",tokenizer=tokenizer,stop_words=stopwords_C50)
然后,我尝试为tfidf
语料库中的每个文档生成一个表示矩阵 X,使用:
X = vectorizer.fit_transform(documents["filename"])
但是,我收到以下错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-152-8c01204baf0e> in <module>
----> 1 X = vectorizer.fit_transform(documents["filename"])
~\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in fit_transform(self, raw_documents, y)
1611 """
1612 self._check_params()
-> 1613 X = super(TfidfVectorizer, self).fit_transform(raw_documents)
1614 self._tfidf.fit(X)
1615 # X is already a transformed view of raw_documents so
~\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in fit_transform(self, raw_documents, y)
1029
1030 vocabulary, X = self._count_vocab(raw_documents,
-> 1031 self.fixed_vocabulary_)
1032
1033 if self.binary:
~\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in _count_vocab(self, raw_documents, fixed_vocab)
941 for doc in raw_documents:
942 feature_counter = {}
--> 943 for feature in analyze(doc):
944 try:
945 feature_idx = vocabulary[feature]
~\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py in <lambda>(doc)
327 tokenize)
328 return lambda doc: self._word_ngrams(
--> 329 tokenize(preprocess(self.decode(doc))), stop_words)
330
331 else:
TypeError: 'list' object is not callable
我该如何解决这个问题?
解决方案
好吧,我想出了自己问题的答案。
如果我将所有参数放入vectorizer
,这样:
vectorizer = TfidfVectorizer()
代码运行得很好。然后,我将输入参数添加回来,它仍然可以正常工作。
vectorizer = TfidfVectorizer(input="filename")
如果我添加停用词也是如此:
vectorizer = TfidfVectorizer(input="filename",stop_words=stopwords_C50)
但是,当我通过标记器时,它会引发错误。
事实证明,我传递给 的参数vectorizer
是一个标记列表,而它应该是另一个函数。
我定义了一个函数stem_tokenizer
如下:
def stem_tokenizer(text):
return [porter_stemmer.stem(token) for token in word_tokenize(text.lower())]
并且,将其传递给vectorizer
:
vectorizer = TfidfVectorizer(input="filename",tokenizer = stem_tokenizer, stop_words=stopwords_C50)
这为我解决了这个问题。
推荐阅读
- sql - SQL Server:如何获取最近 6 周的记录
- android - 在 android 的 kotlin 类中出现多个错误?
- android - Android TV:自定义 SearchFragment 的更好方法是什么——扩展 LeanBack 或从头开始构建 CustomView?
- assembly - 该问题与Assembly x86-32 RET n指令有关
- javascript - 如何自动清除翻转动画事件?
- html - 这是html,css中的哪种消息/对话框?
- php - HTTP 中 GET 和 POST 的区别
- c# - 绑定字段四舍五入十进制值
- java - Azure Service Fabric 中的 Java Spring Boot
- ios - 将 UIScrollView 的交互转移到另一个 UIScrollView 中滚动