【问题标题】:_pickle.UnpicklingError: NEWOBJ class argument isn't a type object_pickle.UnpicklingError: NEWOBJ 类参数不是类型对象
【发布时间】:2022-05-12 20:25:23
【问题描述】:

我在 cmd 上运行了这段代码,我遇到了这个错误。 _pickle.UnpicklingError: NEWOBJ class argument isn't a type object

我的 app.py 是这样的:

# -*- coding: utf-8 -*-
"""
Created on Wed Apr 21 19:18:42 2021

@author: Agni Sain
"""
from flask import Flask,request,render_template
import pandas as pd
import numpy as np
import pickle

app=Flask(__name__)
with open('xgb.pkl','rb') as f:
    xgb=pickle.load(f)

@app.route('/')    
def home():
    return render_template("index.html")   

    
@app.route('/predict',methods=["POST"])
def predict_heart_disease():
    
    age=request.form['age']
    sex=request.form['sex']
    cp = request.form['cp']
    trestbps = request.form['trestbps']
    chol = request.form['chol']
    fbs = request.form['fbs']
    restecg = request.form['restecg']
    thalach = request.form['thalach']
    exang = request.form['exang']
    oldpeak = request.form['oldpeak']
    slope = request.form['slope']
    ca = request.form['ca']
    thal = request.form['thal']
    
    pvalues=[[age,sex,cp,trestbps,chol,fbs,restecg,thalach,exang,oldpeak,slope,ca,thal]]
    pvalues=np.array(pvalues).reshape((1,-1))
    pred=xgb.predict(pvalues)
    predf=float(pred)
    return render_template('result.html', data=predf)

@app.route('/predict_file',methods=["POST"])    
def predict_heart_disease_file():
    df_test=pd.read_csv(request.files.get("file"))
    
    prediction=xgb.predict(df_test)
    return str((list(prediction)))
    
if (__name__=='__main__'):
    app.run()

我确实在UnpicklingError: NEWOBJ class argument isn't a type object 上读到过这个错误,但没有从中找到任何帮助。谁能简单地说一下为什么会出现这个错误以及如何解决它?

【问题讨论】:

  • 嘿!感谢您的支持,但我不得不用其他模型更改 pkl 文件。我的项目迟到了,可能会对截止日期造成更多伤害。抱歉回复晚了。
  • 是的,我确实检查了您的答案。造成的问题主要是xgboost的版本造成的。
  • 我必须切换到梯度提升分类器,它工作正常。

标签: python pickle xgboost


【解决方案1】:

原因,正如thread 中所讨论的,由于XGBClassifier 直接与scikit-learn API 交互,因此也需要将其安装在远程服务器上。如果您使用 xgboost.booster 类(原生 xgboost 模型,而不是 scikit-learn 类型模型),它会正常工作。
此外,按照model I/O page 进行保存和加载应该不会出错。
另一个“答案”不正确,错误并非源于数据框为空/无。

【讨论】:

    【解决方案2】:

    需要添加if语句

    df_test=pd.read_csv(request.files.get("file"))
    if not df_test.empty:
       prediction=xgb.predict(df_test)
       return str((list(prediction)))
    else:
       return None
    

    【讨论】:

      【解决方案3】:

      确保在酸洗之前和取消酸洗时创建 XGBClassifier 时使用相同的 scikit-learn 版本

      【讨论】:

        猜你喜欢
        • 2013-07-05
        • 1970-01-01
        • 1970-01-01
        • 2021-11-06
        • 2021-08-05
        • 2021-07-07
        • 1970-01-01
        • 2021-08-18
        • 2021-08-29
        相关资源
        最近更新 更多