【问题标题】:Loaded model has incorrect number of features加载的模型的特征数量不正确
【发布时间】:2019-08-21 14:18:19
【问题描述】:

我正在使用 sci-kitlearn 和 pickle(为了保存我训练过的模型)。

首先,执行以下代码:

from sklearn.linear_model import LogisticRegression

logreg = LogisticRegression(solver='lbfgs', multi_class='auto')
logreg.fit(X_train, y_train)

with open('text_classifier', 'wb') as picklefile:
    pickle.dump(logreg, picklefile)

当我以后想再次使用这个模型时,我会使用(检查它是否仍然有效):

with open('text_classifier', 'rb') as training_model:
    model = pickle.load(training_model)

print('Accuracy of Logistic regression classifier on test set: {:.2f}\n'
      .format(model.score(X_test, y_test)))

但是,这会引发以下错误:

ValueError: X has 74 features per sample; expecting 77

有人可以向我解释为什么会这样吗?

【问题讨论】:

    标签: python scikit-learn pickle


    【解决方案1】:

    您确定 train 和 test 中的列相同吗?显然,您的 X_test 集有 74 列,而模型预计有 77 列。 你在训练之前对数据进行过采样吗?可能是因为采样不当。

    如果您的数据集完好无损,那么这应该可以正常工作:

    pickle.dump(logreg, open('text_classifier.sav', 'wb'))
    model = pickle.load(open('text_classifier.sav', 'rb'))
    

    这可能会有所帮助:关于模型持久性的 Scikit-learn 文档(pickle 和 joblib): https://scikit-learn.org/stable/modules/model_persistence.html

    【讨论】:

    • 只运行这两行就可以正常工作,只是在单独执行时不起作用
    • 在我发布的链接(sklearn 文档)中,唯一提到在单独的 python 进程中使用模型是页面建议使用joblib 而不是pickle。尝试使用 joblib。使用from joblib import dump, load 保存模型,然后使用dump(logreg, 'text_classifier.joblib'),然后使用model = load('text_classifier.joblib') 加载
    • 我还是有同样的问题
    猜你喜欢
    • 2013-09-17
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 2021-08-17
    相关资源
    最近更新 更多