我使用随机森林构建了一个垃圾邮件分类器,并希望创建一个单独的函数来将文本消息分类为垃圾邮件或正常邮件,我尝试了以下代码:
def predict_message(pred_text): pred_text=[pred_text] pred_text2 = tfidf_vect.fit_transform(pred_text) pred_features = pd.DataFrame(pred_text2.toarray()) prediction = rf_model.predict(pred_features) return (prediction)pred_text = "how are you doing today?"prediction = predict_message(pred_text)print(prediction)
但它给出了以下错误:
The number of features of the model must match the input.Model n_features is 7985 and input n_features is 1
我看不出问题所在,如何才能使它正常工作?
回答:
通过调用tfidf_vect.fit_transform(pred_text)
,你的向量化器会丢失来自原始训练语料库的所有信息。
你应该只调用transform
。
以下更改应该有帮助:
def predict_message(pred_text): pred_text=[pred_text] pred_text2 = tfidf_vect.transform(pred_text) # 已更改 prediction = rf_model.predict(pred_text2) return (prediction)pred_text = "how are you doing today?"prediction = predict_message(pred_text)print(prediction)