在try 使用FlaskTM将机器学习模型部署到Vercel时,我收到以下错误:

Traceback (most recent call last):
 File "./index.py", line 16,
 in load_models model = OnlineLearningModel.load("exchange_model.pkl")
 File "/var/task/在线学习模型.py", line 65,
   in load obj = joblib.load(f)
 File "/var/task/joblib/numpy_pickle.py", line 648,
   in load obj = _unpickle(fobj)
 File "/var/task/joblib/numpy_pickle.py", line 577,
   in _unpickle obj = unpickler.load()
 File "/var/lang/lib/python3.9/pickle.py", line 1212,
   in load dispatch[key[0]](self)
 File "/var/lang/lib/python3.9/pickle.py", line 1537,
   in load_stack_global self.append(self.find_class(module, name))
 File "/var/lang/lib/python3.9/pickle.py", line 1581,
   in find_class return _getattribute(sys.modules[module], name)[0] 
 File "/var/lang/lib/python3.9/pickle.py", line 331,
   in _getattribute raise AttributeError("Can't get attribute {!r} on {!r}"
 AttributeError: Can't get attribute 'OnlineLearningModel' on <module '__main__' from '/var/runtime/bootstrap.py'

我试着按照this link中的建议go 做,但错误仍然存在.当我在电脑上本地部署时,这款应用运行得很好,但在Vercel上却不行.我添加了一个Try/Catch来定位错误

Here is my folder structure and files
enter image description here

index.py

    from flask import Flask, render_template, request
    from sklearn.linear_model import SGDRegressor
    from sklearn.preprocessing import StandardScaler
    from online_learning_model import OnlineLearningModel
    import joblib
    
    
    app = Flask(__name__)
    
    def load_models():
        try:
            model = OnlineLearningModel.load("exchange_model.pkl")
            error_message = None
            return model, error_message
        except Exception as error:
            error_message = f"Model could not be loaded due to error: {error}"
            return None, error_message
@app.route("/", methods=["GET", "POST"])
def home():
    model, error_message = load_models()
    result_message = error_message

    if request.method == "POST":
        result_message = "Testing"

    return render_template("index.html", result=result_message)


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

在线学习模型.py

from sklearn.linear_model import SGDRegressor
from sklearn.preprocessing import StandardScaler
import joblib


class OnlineLearningModel:
    def __init__(self):
        self.sgd = SGDRegressor(loss="squared_loss", penalty="l2", random_state=0)
        self.scaler = StandardScaler()

    def predict(self, year):
        X_new_scaled = self.scaler.transform([[year]])
        y_pred = self.sgd.predict(X_new_scaled)
        y_pred_rounded = round(y_pred[0], 4)
        return y_pred_rounded

    @staticmethod
    def load(fileName):
        with open(fileName, "rb") as f:
            obj = joblib.load(f)
        return obj

Vercel.json

{
    "builds": [
        {
            "src": "index.py",
            "use": "@vercel/python"
        },
        {
            "src": "static/**",
            "use": "@vercel/static"
        }
    ],
    "routes": [
        {
            "src": "/(.*)",
            "dest": "/"
        }
    ]
}

推荐答案

我通过将类OnlineLearningModel移动到另一个文件learning_model.py,然后将其导入到index.py来解决这个问题

from learning_model import OnlineLearningModel 

然后我在index.py文件中添加了这个修复程序

import __main__
__main__.OnlineLearningModel = OnlineLearningModel

Python相关问答推荐

计算相同形状的两个张量的SSE损失

Class_weight参数不影响RandomForestClassifier不平衡数据集中的结果

Pandas 填充条件是另一列

如何使用pandasDataFrames和scipy高度优化相关性计算

max_of_three使用First_select、second_select、

numba jitClass,记录类型为字符串

Pandas 滚动最接近的价值

沿着数组中的轴计算真实条目

Pandas 都是(),但有一个门槛

如何在Django基于类的视图中有效地使用UTE和RST HTIP方法?

将pandas Dataframe转换为3D numpy矩阵

Django RawSQL注释字段

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

Python Pandas获取层次路径直到顶层管理

在Python中调用变量(特别是Tkinter)

使用Python查找、替换和调整PDF中的图像'

根据客户端是否正在传输响应来更改基于Flask的API的行为

从嵌套极轴列的列表中删除元素

无法在盐流道中获得柱子

如何在PYTHON中向单元测试S Side_Effect发送额外参数?