如何在HTML中展示Flask机器学习模型的输出结果?
解决方案
一、修复后端JSON序列化错误
这个错误是因为你返回的JSON数据里包含了无法被序列化的类型(比如numpy数值、未定义变量、自定义对象),需要先把数据转成Python原生可序列化类型:
- 机器学习模型返回的numpy数值,转成
float()或int()原生类型 - 自定义对象要先转成字典格式
- 排查是否有未赋值就返回的变量
修改后的server.py核心示例:
from flask import Flask, request, jsonify import json import numpy as np app = Flask(__name__) @app.route('/predict', methods=['POST']) def predict(): # 获取上传文件 params_file = request.files.get('params') image_file = request.files.get('image') # 解析参数文件 params = json.load(params_file) # 替换为你的机器学习模型处理逻辑 model_float_result = np.float32(0.87) model_str_result = "预测类别:猫" model_json_result = {"置信度": model_float_result, "类别": model_str_result} # 转换为可序列化的原生类型 serializable_data = { "置信度": float(model_json_result["置信度"]), "类别": model_json_result["类别"] } return jsonify(serializable_data) @app.route('/') def index(): return app.send_static_file('index.html') if __name__ == '__main__': app.run(debug=True)
二、前端实现同页面异步提交与结果展示
用AJAX(Fetch API)提交表单,避免页面刷新,直接在当前页面展示结果:
修改index.html,添加结果展示区域:
<!DOCTYPE html> <html> <head> <title>机器学习预测</title> </head> <body> <form id="predForm"> <label>参数JSON文件:</label> <input type="file" name="params" accept=".json" required><br> <label>图片文件:</label> <input type="file" name="image" accept="image/*" required><br> <button type="submit">提交预测</button> </form> <!-- 结果展示区,初始隐藏 --> <div id="resultBox" style="margin-top:20px; display:none;"> <h3>预测结果</h3> <p>置信度:<span id="confidence"></span></p> <p>类别:<span id="classResult"></span></p> </div> <script src="script.js"></script> </body> </html>
修改script.js处理异步请求:
document.getElementById('predForm').addEventListener('submit', async function(e) { e.preventDefault(); // 阻止表单默认刷新行为 const formData = new FormData(this); try { const response = await fetch('/predict', { method: 'POST', body: formData }); if (!response.ok) { throw new Error('请求失败,请检查后端服务'); } const result = await response.json(); // 显示并填充结果 const resultBox = document.getElementById('resultBox'); resultBox.style.display = 'block'; document.getElementById('confidence').textContent = result.置信度.toFixed(2); document.getElementById('classResult').textContent = result.类别; } catch (error) { alert('预测出错:' + error.message); } });
三、关键注意事项
- 前端表单的
name属性值(params、image)必须和后端request.files.get()里的参数名完全一致 - 如果模型返回复杂JSON结构,只需保证后端输出的所有值都是Python原生类型(str、int、float、list、dict),前端对应解析即可
- 调试时打开浏览器控制台(F12),查看网络请求的返回结果,能快速定位问题
内容的提问来源于stack exchange,提问作者user10650761
相关产品推荐
相关产品推荐

