我试图用Python对pandas数据框进行预测。不知道为什么CountVectorizer不能转换数据。有人知道是什么原因导致了这个问题吗?
这是我的代码。
filename = 'final_model.sav'
print(response.status_code)
data = response.json()
print(data)
dictionary = pd.read_json('rating_company_small.json', lines=True)
dictionary_df = pd.DataFrame()
dictionary_df["comment text"] = dictionary["comment"]
data = pd.DataFrame.from_dict(json_normalize(data), orient='columns')
print(data)
df = pd.DataFrame()
df["comment text"] = data["Text"]
df["status"] = data["Status"]
print(df)
Processing.dataframe_cleaning(df)
comment_data = df['comment text']
tfidf = CountVectorizer()
tfidf.fit(dictionary_df["comment text"])
Test_X_Tfidf = tfidf.transform(df["comment text"])
print(comment_data)
print(Test_X_Tfidf)
loaded_model = pickle.load(open(filename, 'rb'))
predictions_NB = loaded_model.predict(Test_X_Tfidf)
这是数据框架
comment text status
0 [slecht, bedrijf] string
1 [leuk, bedrijfje, goed, behandeld] Approved
2 [leuk, bedrijfje, goed, behandeld] Approved
3 [leuk, bedrijfje] Approved
完整的错误信息。
Traceback (most recent call last):
File "Request.py", line 36, in <module>
Test_X_Tfidf = tfidf.transform(df["comment text"])
File "C:\Users\junio\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 1112, in transform
_, X = self._count_vocab(raw_documents, fixed_vocab=True)
File "C:\Users\junio\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 970, in _count_vocab
for feature in analyze(doc):
File "C:\Users\junio\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 352, in <lambda>
tokenize(preprocess(self.decode(doc))), stop_words)
File "C:\Users\junio\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 256, in <lambda>
return lambda x: strip_accents(x.lower())
AttributeError: 'list' object has no attribute 'lower'
我希望它能返回数据框架上的预测。
CountVectorizer
不能直接处理 Series
的列表,这就是为什么你会收到那个错误(lower
是一个字符串方法).我看起来你想要一个 MultiLabelBinarizer
来代替,它可以处理这种输入结构。
from sklearn.preprocessing import MultiLabelBinarizer
count_vec = MultiLabelBinarizer()
mlb = count_vec.fit(df["comment text"])
pd.DataFrame(mlb.transform(df["comment text"]), columns=[mlb.classes_])
bedrijf bedrijfje behandeld goed leuk slecht
0 1 0 0 0 0 1
1 0 1 1 1 1 0
2 0 1 1 1 1 0
3 0 1 0 0 1 0
但是上面的方法不会考虑到列表中的重复元素,输出元素可以是: 0
或 1
. 如果这是你所期望的行为,你可以将这些列表加入到字符串中,然后用 然后 用 CountVectorizer
,因为它期待的是字符串。
text = df["comment text"].map(' '.join)
count_vec = CountVectorizer()
cv = count_vec.fit(text)
pd.DataFrame(cv.transform(text).toarray(), columns=[mlb.classes_])
bedrijf bedrijfje behandeld goed leuk slecht
0 1 0 0 0 0 1
1 0 1 1 1 1 0
2 0 1 1 1 1 0
3 0 1 0 0 1 0
请注意,这个 不是 无异于 tf-idf
的输入字符串。在这里,你只需要有实际的计数。为此,你有 TfidfVectorizer
对于同样的例子,会产生:
bedrijf bedrijfje behandeld goed leuk slecht
0 0.707107 0.000000 0.000000 0.000000 0.000000 0.707107
1 0.000000 0.444931 0.549578 0.549578 0.444931 0.000000
2 0.000000 0.444931 0.549578 0.549578 0.444931 0.000000
3 0.000000 0.707107 0.000000 0.000000 0.707107 0.000000