模型的特征数量必须与输入匹配模型 n_features 为 7985,输入 n_features 为 1

问题描述

我用随机森林构建了一个垃圾邮件分类器,并想创建一个单独的函数来将文本消息分类垃圾邮件或火腿,我尝试了:

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)  # Changed
    prediction = rf_model.predict(pred_text2)
    return (prediction)

pred_text = "how are you doing today?"

prediction = predict_message(pred_text)
print(prediction)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...