怎么将返回的prediction,在文本框的网页中显示
from flask import Flask, render_template, request
import pickle
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
# 从表单中获取用户输入的文本
title = request.form['title']
x = int(str(torch.argmax(model(word2vec(title))))[-2])
x = str(x)
print(x)
# 将预测结果作为参数传递给结果页面,并显示结果
# return render_template('index.html', prediction=x, description=description)
return render_template('index.html', prediction=x, description=x)
# 显示包含title的文本框和提交按钮的表单页面
return '''
<!DOCTYPE html>
<html>
<head>
<title>My Awesome Webpage</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
form {
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
</style>
</head>
<body>
<div>
<form>
<label for="title">请输入待检测文本:</label>
<br>
<textarea id="title" name="title" required style="width: 600px; height: 200px;"></textarea>
<br>
<br> <!-- 添加一个换行符 -->
<label for="description">检测结果为:</label>
<br>
<input type="text" id="description" name="description" value={{ prediction }}>
<br>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
'''
if __name__ == '__main__':
app.run()
返回模板的时候,将那个值用花括号或起来,以键值对的方式返回
我可以根据您的问题提供以下解决方案: 1. 将机器学习模型嵌入Flask应用程序中,然后在相应的视图函数中调用模型并获取预测结果。 2. 在Flask的HTML模板中使用Jinja2模板引擎,在文本框中显示预测结果。
以下是代码示例:
# 导入必要的库和模型
from flask import Flask, request, render_template
from sklearn.externals import joblib
app = Flask(__name__)
# 加载机器学习模型
model = joblib.load('model.pkl')
@app.route('/', methods=['GET', 'POST'])
def home():
# 如果是POST请求,则获取表单数据并调用机器学习模型进行预测
if request.method == 'POST':
# 获取表单数据
feature1 = request.form.get('feature1')
feature2 = request.form.get('feature2')
# 调用机器学习模型进行预测
result = model.predict([[feature1, feature2]])
# 返回渲染好的HTML模板,并将预测结果传递给模板
return render_template('index.html', result=result)
# 如果是GET请求,则渲染HTML模板
else:
return render_template('index.html')
在模板中,您可以使用以下语法将预测结果显示在文本框中:
<input type="text" name="result" value="{{result}}" />
注意,在模板中不能直接访问Python变量,需要使用{{}}
将变量包含起来,并在渲染HTML模板时传递变量。