【问题标题】:Why am I facing the Unpickling Error while trying to load my model in Flask?为什么我在尝试在 Flask 中加载模型时遇到 Unpickling 错误?
【发布时间】:2020-03-07 18:41:37
【问题描述】:

我在 jupyter 实验室中尝试了酸洗和解酸,它似乎可以正常工作,但是当我运行我的 app.py 时,它给了我以下错误。

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Python 3.7\fakenews\venv\lib\site-packages\sklearn\utils\deprecation.py:144: FutureWarning: The sklearn.linear_model.passive_aggressive module is  deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.linear_model. Anything that cannot be imported from sklearn.linear_model is now part of the private API.
  warnings.warn(message, FutureWarning)
Traceback (most recent call last):
  File "app.py", line 9, in <module>
    model = pickle.load(open('model.pkl', 'rb'))
_pickle.UnpicklingError: invalid load key, '\x17'.

这是我的文件。 模型.py

import pandas as pd
import itertools
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import PassiveAggressiveClassifier
from sklearn.metrics import accuracy_score, confusion_matrix
#Read the data
df=pd.read_csv('C:\\Users\\Hp\\Desktop\\mini project\\news\\news.csv')
#Get shape and head
df.shape
df.head()
#DataFlair - Get the labels
labels=df.label
labels.head()
#DataFlair - Split the dataset
x_train,x_test,y_train,y_test=train_test_split(df['text'], labels, test_size=0.2, random_state=7)
#DataFlair - Initialize a TfidfVectorizer
tfidf_vectorizer=TfidfVectorizer(stop_words='english', max_df=0.7)
#DataFlair - Fit and transform train set, transform test set
tfidf_train=tfidf_vectorizer.fit_transform(x_train) 
tfidf_test=tfidf_vectorizer.transform(x_test)
#DataFlair - Initialize a PassiveAggressiveClassifier
pac=PassiveAggressiveClassifier(max_iter=50)
pac.fit(tfidf_train,y_train)
#DataFlair - Predict on the test set and calculate accuracy
y_pred=pac.predict(tfidf_test)
score=accuracy_score(y_test,y_pred)
print(f'Accuracy: {round(score*100,2)}%')
#DataFlair - Build confusion matrix
confusion_matrix(y_test,y_pred, labels=['FAKE','REAL'])

应用程序.py



import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
import pandas as pd
app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))
session.clear()
@app.route('/')
def home():
    return render_template('index.html')

@app.route('/predict',methods=['POST'])
def predict():

    news = request.form["newsT"]
    test1 = pd.Series(news, index=[11000])
    prediction = model.predict(test1)
    return render_template('index.html', prediction_text='Sales should be $ {}'.format(prediction))



if __name__ == "__main__":
    app.run(debug=True)

我用这段代码腌制---------------


# Save the model as a pickle in a file 
joblib.dump(pac, 'model.pkl') 

# Load the model from the file 
pac_from_joblib = joblib.load('model.pkl')  

# Use the loaded model to make predictions 
pac_from_joblib.predict(tfidf_test) 

这在实验室中运行良好,但在加载 app.py 时似乎会出现 unpickling 错误。 我对这个领域还很陌生,即使在网上进行了广泛的搜索后,我也无法找出问题所在。

【问题讨论】:

    标签: python machine-learning scikit-learn pickle


    【解决方案1】:

    这似乎是一个编码问题。这可能是因为您是 joblib 来保存泡菜模型并尝试加载相同的模型 vai pickle 库。尝试使用joblib再次加载模型

    model = joblib.load('model.pkl')
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-01
      • 1970-01-01
      • 2022-01-26
      • 2020-06-01
      • 1970-01-01
      相关资源
      最近更新 更多