gpt4 book ai didi

python - TFIDF 向量器给出错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:37:41 26 4
gpt4 key购买 nike

我正在尝试使用 TFIDF 和 SVM 对某些文件进行文本分类。一次要选择 3 个单词的特征。我的数据文件已经采用以下格式:angel eyes has, each one for, on its own.没有停用词,也不能做 lemming 或 stemming。我希望该功能被选为:angel eyes has ...我写的代码如下:

import os
import sys
import numpy
from sklearn.svm import LinearSVC
from sklearn.metrics import confusion_matrix
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics
from sklearn.datasets import load_files
from sklearn.cross_validation import train_test_split

dt=load_files('C:/test4',load_content=True)
d= len(dt)
print dt.target_names
X, y = dt.data, dt.target
print y
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
print y_train
vectorizer = CountVectorizer()
z= vectorizer.fit_transform(X_train)
tfidf_vect= TfidfVectorizer(lowercase= True, tokenizer=',', max_df=1.0, min_df=1, max_features=None, norm=u'l2', use_idf=True, smooth_idf=True, sublinear_tf=False)


X_train_tfidf = tfidf_vect.fit_transform(z)

print tfidf_vect.get_feature_names()
svm_classifier = LinearSVC().fit(X_train_tfidf, y_train)

不幸的是,我在“X_train_tfidf = tfidf_vect.fit_transform(z)”处遇到错误: AttributeError:未找到较低的。
如果我修改代码来做

tfidf_vect= TfidfVectorizer( tokenizer=',', use_idf=True, smooth_idf=True, sublinear_tf=False)
print "okay2"
#X_train_tfidf = tfidf_transformer.fit_transform(z)
X_train_tfidf = tfidf_vect.fit_transform(X_train)
print X_train_tfidf.getfeature_names()

我收到错误:TypeError: 'str' object is not callable可以请有人告诉我我哪里错了

最佳答案

tokenizer 参数的输入是可调用的。尝试定义一个函数来适本地标记您的数据。如果是逗号分隔则:

def tokens(x):
return x.split(',')

应该可以。

from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vect= TfidfVectorizer( tokenizer=tokens ,use_idf=True, smooth_idf=True, sublinear_tf=False)

创建一个由,分隔的随机字符串

 a=['cat on the,angel eyes has,blue red angel,one two blue,blue whales eat,hot tin roof']

tfidf_vect.fit_transform(a)
tfidf_vect.get_feature_names()

返回

Out[73]:

[u'angel eyes has',
u'blue red angel',
u'blue whales eat',
u'cat on the',
u'hot tin roof',
u'one two blue']

关于python - TFIDF 向量器给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28103992/

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