如何通过 Flask 中的下拉菜单 select 数据帧索引?

Ηow to select a dataframe index via a dropdown menu in Flask?

上下文和我想做的事情:

你好,这里有一个 iris 数据集的例子。 我已经导入了我的机器学习模型,我的网络应用程序想法是:

那样的话,我只需要 select 测试集行,模型就会自动获得 x_test 特征来进行估计。

问题:

我的问题是出现了下拉菜单,但我无法在其中 select 进行任何操作。我觉得我快完成了,但我不知道问题出在哪里(这是我的第一个烧瓶项目),你知道怎么做吗?非常感谢您的帮助,这是我的代码:

我的代码:

- app.py :

# libraries
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split 
import piskle
from flask import Flask, request, jsonify, render_template

app = Flask(__name__) # initialization
model = piskle.load('model.pskl') # model
iris = pd.read_csv('iris.csv') # dataset
X = iris[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']]
y = iris['species']
x_train,x_test,y_train,y_test = train_test_split(X,y, test_size=0.3, random_state=0)


@app.route('/') # homepage
def home():
    return render_template('index.html')

@app.route('/predict',methods=['POST']) # estimation
def predict():

    index_list = x_test.index.to_list()
    feat = [x_test.iloc[i] for i in index_list]
    final_feat = np.array(feat).reshape(1, -1) 
    prediction = model.predict(pd.DataFrame(final_feat))    

    # result
    return render_template('index.html', index_list=index_list, prediction_text='Predicted Class: {}'.format(prediction))

if __name__ == "__main__":
    app.run(debug=True)

- index.html :

<!DOCTYPE html>
<html >
<!-- Titre et fichier/police CSS -->
<head>
  <meta charset="UTF-8">
  <title>Iris classifier web-app</title>
</head>
<body>
 <div>
    <h1>Predict Iris Class</h1>

    <form action="{{ url_for('predict')}}"method="post">
         
        <select name="index_list" method="GET" action="/">
        {% for i in index_list %}
                <option value="{{ i }}">{{ i }}</option>
            {% endfor %}
        </select>

   <br>
   <br>
        <button type="submit" class="btn btn-primary btn-block btn-large">Predict</button>
    </form>
   <br>
   <br>
   {{ prediction_text }}
 </div>
</body>
</html>

不确定如何回答您的问题。复制粘贴此代码并告诉我它是否按照您想要的方式工作。

我想这些项目没有出现是因为你打开了 "/" 路线而不是 "/predict",或者可能是因为你的 .index_to_list() 方法没有 return 列表完全没有。


main.py:

from flask import Flask, render_template, request

app = Flask(__name__)


@app.route('/predict', methods=['GET', 'POST'])  # estimation
def predict():
    index_list = [1, 2, 3, 4]

    prediction = 0

    chosen_option = None

    if request.method == 'POST':
        default_value = 0
        chosen_option = request.form.get(
            key='select_name',
            default=default_value,
        )
        chosen_option = int(chosen_option)

    # your prediction code goes into calc_prediction
    prediction = calc_prediction(chosen_option=chosen_option)

    return render_template(
        template_name_or_list='index.html',
        index_list=index_list,
        prediction=prediction,
        chosen_option=chosen_option,
    )


def calc_prediction(chosen_option: int):
    prediction = 0
    if not chosen_option:
        return 0
    
    # Do your prediction calculatoins (I guess your prediction were somehow based on
    # options from select)

    print(type(chosen_option))
    print(chosen_option)
    prediction = chosen_option / 4

    return prediction


if __name__ == "__main__":
    app.run(debug=True)

index.html:

<!DOCTYPE html>
<html>
<!-- Titre et fichier/police CSS -->
<head>
  <meta charset="UTF-8">
  <title>Iris classifier web-app</title>
</head>
<body>
 <div>
    <h1>Predict Iris Class</h1>

    <form action="{{ url_for('predict')}}" method="post">
        <select name="select_name">
        {% for i in index_list %}
            <option value="{{ i }}">{{ i }}</option>
        {% endfor %}
        </select>
        <br>
        <br>
        <button type="submit">Predict</button>
    </form>
   <br>
   <p>Predicted Class: {{ prediction }}</p> 
   <p>Chosen option: {{ chosen_option }}</p> 
 </div>
</body>
</html>