Heroku部署Flask股票预测模型应用遇文件找不到错误
问题描述
制作股票预测模型并通过Pickle保存后,将其集成到Flask代码中部署至Heroku,推送应用后出现Application error。本地用Postman测试main.py运行完全正常,但部署后打开应用显示:
Application error
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command
heroku logs --tail
查看Heroku日志,发现具体错误:
2023-12-18T14:55:25.125742+00:00 app[web.1]: raise FileNotFoundError(f"Model file not found at: {model_path}")
2023-12-18T14:55:25.125742+00:00 app[web.1]: FileNotFoundError: Model file not found at: C:/Users/Anik/PycharmProjects/ML/models/model
相关代码文件
main.py
import os import pickle as pk from flask import Flask, request, jsonify import numpy as np app = Flask(__name__) model_path = 'models/model' if not os.path.exists(model_path): raise FileNotFoundError(f"Model file not found at: {model_path}") with open(model_path, 'rb') as model_file: model = pk.load(model_file) @app.route('/') def index(): return "Hello world" @app.route('/predict', methods=['POST']) def predict(): try: sex = float(request.form.get('sex')) age = float(request.form.get('age')) hypertension = int(request.form.get('hypertension')) disease = int(request.form.get('disease')) work = int(request.form.get('work')) glucose = float(request.form.get('glucose')) bmi = float(request.form.get('bmi')) smoking = int(request.form.get('smoking')) input_query = np.array([[sex, age, hypertension, disease, work, glucose, bmi, smoking]]) result = model.predict(input_query)[0] return jsonify({'placement': str(result)}) except Exception as e: return jsonify({'error': str(e)}) if __name__ == '__main__': app.run(debug=True)
requirements.txt
Flask==3.0.0 gunicorn==21.2.0 numpy==1.26.2 scikit-learn==1.3.2
.gitignore
__pycache__ *.pyc *.pyo *.pyd *.db *.sqlite venv/
Procfile
web: gunicorn main:app
解决方案
1. 确保模型文件被提交到Git仓库
- 确认本地项目中
models文件夹存在,且包含model文件 - 执行命令将模型文件夹加入Git追踪:
git add models/ - 提交更改并重新推送到Heroku:
git commit -m "Add model files to repo" git push heroku main
2. 修改路径构建方式,避免环境差异
将main.py中model_path的定义改为基于当前文件的绝对路径,确保在任何环境下都能正确定位模型文件:
model_path = os.path.join(os.path.dirname(__file__), 'models', 'model')
此代码会自动根据main.py所在目录生成模型文件的正确路径,避免因工作目录变化导致的路径错误。
内容的提问来源于stack exchange,提问作者Toufic Ahmed

