我有一个下拉列表,可以从中选择不同类型的回归。到目前为止,我已经实现了线性回归。如果我从列表中选择线性回归并按下预测按钮,则会显示该回归的图解图。我已经使用post方法处理了此问题,将选择值从html发送到python。但是一段时间后,这个数字消失了。我不知道如何解决此问题,以便在页面上进行进一步修改之前显示该图。这是html正文:
<body>
<form method="post">
<select size="1" style="width: 252px" id="select_prediction_id"
name="select_prediction_id">
<option hidden="true">{{ _("Select an algorithm from the list") }}</option>
<option value="1">{{ _("Linear Regression") }}</option>
<option value="2">{{ _("Polynomial Regression") }}</option>
<option value="3">{{ _("Spline Regression") }}</option>
<option value="4">{{ _("Facebook Prophet") }}</option>
</select>
<input type="submit" id="send_message" name="send_message" class="btn btn-outline-secondary"
value="{{ _("Predict") }}" onclick="show_plot()"/>
</form>
<div class="chart" id="pred_plot">
<script>
function show_plot() {
var selected_prediction = document.getElementById("select_prediction_id");
var selected_prediction_id = selected_prediction.options[selected_prediction.selectedIndex].value;
if (selected_prediction_id === "1") {
var graphs = {{lin_reg_py | safe}};
Plotly.plot('pred_plot', graphs, {});
}
}
</script>
</div>
</body>
这是预测方法的代码,该代码从另一个python脚本调用一些方法,该脚本计算回归。另外,我如何在按下按钮之前计算回归?我想在更改选择的值时进行计算。
@app.route("/predictions",methods=["POST","GET"])
def calculate_predictions():
if request.method == "POST":
if request.form["select_prediction_id"] != "Select an algorithm from the list":
select_prediction = request.form["select_prediction_id"]
group_by_df, X_train, sensor_name = calculate_linear_regression(
"https://raw.githubusercontent.com/iulianastroia/csv_data/master/final_dataframe.csv", "ch2o")
linear_regression_fig = create_figure(group_by_df, X_train, sensor_name)
return render_template("predictions.html", lin_reg_py=linear_regression_fig)
return render_template("predictions.html")
以所有结构形式进行的方式,您需要将请求方法设为POST才能使图形首先显示。如果要在某人第一次显示图像后保留该图像,则可以尝试缓存该图像。已经设置了This package来执行此操作,但是您也可以在全局范围内定义一个自定义类以实现相同的效果。
class PlotlyImage:
def __init__(self):
self.img = None
plotlyimg = PlotlyImage()
@app.route("/predictions",methods=["POST","GET"])
def calculate_predictions():
if request.method == "POST":
if request.form["select_prediction_id"] != "Select an algorithm from the list":
select_prediction = request.form["select_prediction_id"]
group_by_df, X_train, sensor_name = calculate_linear_regression(
"https://raw.githubusercontent.com/iulianastroia/csv_data/master/final_dataframe.csv", "ch2o")
plotlyimg.img = create_figure(group_by_df, X_train, sensor_name)
if plotlyimg.img is not None:
return render_template("predictions.html", lin_reg_py=plotlyimg.img)
return render_template("predictions.html")
作为一项好处,即使您离开并稍后再返回,也可以使图像停留在页面上。