用csv格式存储的大概1000个样本数据5个输入点1个输出进行回归预测,用神经网络训练保存成了.pth的模型文件。在flask方面我想做简单的5输入值1输出值的一个预测界面,调用模型并将预测值显示在flask界面上,但网上教学案例多是图像识别,对于我这类基础的表格数据没有适当的案例,想问一下如果从输入框获取输入值,应该怎样将其导入模型中。
我自己尝试写了一下,但是始终报错并无法达到目的。请教大家这该怎样修改。
from flask import Flask, render_template, request,jsonify
import torch
import pandas as pd
import numpy as np
from torch.autograd import Variable
model_file_path = 'D:\python files\PyTorch\modelA[4layer,32,10000].pth'
app=Flask(__name__)
use_gpu = True
@app.route('/query')
def query():
return render_template('query.html')
@app.route('/getdata', methods=['GET','POST'])
def getdata():
if request.method=='POST':
x1 = request.form.get('x1')
x2 = request.form.get('x2')
x3 = request.form.get('x3')
x4 = request.form.get('x4')
x5 = request.form.get('x5')
Y=predict(x1,x2,x3,x4,x5)
return Y
class neu(torch.nn.Module):
def __init__(self):
super(neu, self).__init__()
self.linear1 = torch.nn.Linear(5,12)
self.linear2 = torch.nn.Linear(12,45)
self.linear3 = torch.nn.Linear(45, 32)
self.linear4 = torch.nn.Linear(32, 12)
self.linear5 = torch.nn.Linear(12, 1)
self.activate = torch.nn.ReLU()
def forward(self, x):
x = self.activate(self.linear1(x))
x = self.activate(self.linear2(x))
x = self.activate(self.linear3(x))
x = self.activate(self.linear4(x))
x = self.activate(self.linear5(x))
return x
def loadmodel(file_PATH):
model = neu()
predictmodel = model.load_state_dict(torch.load(file_PATH))
return predictmodel
htmlmodel = loadmodel(model_file_path)
def predict(x1,x2,x3,x4,x5):
features = [x1,x2,x3,x4,x5]
predictvalue = htmlmodel(features)
predictvalue = predictvalue.data.numpy()
return predictvalue
if __name__ == '__main__':
app.run(host='0.0.0.0',port='5000')
######报错内容:TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.