如何在Flask中适配机器学习模型的分类变量前端输入?
解决方案
1. 前端友好化修改
把当前下拉选框的value值替换为真实技术名称,让用户直观看到并选择选项,完全避开编码数字。修改后的HTML代码如下:
<br> <label for="Other_technologies">Other technologies you know</label> <select id="Other_technologies" name="Other_technologies"> <option value="C/C++">C/C++</option> <option value="Javascript">Javascript</option> <option value="Kotlin">Kotlin</option> <option value="Python">Python</option> <option value="SQL">SQL</option> </select> <br>
2. 后端映射用户输入到哑编码
由于你用pd.get_dummies(df['Other_technologies'], drop_first=True)生成哑编码(drop_first=True会将C/C++设为参考组,不生成它的哑编码列),后端需要把用户提交的选项转换成模型所需的0/1特征值:
核心逻辑
- 先明确模型训练时生成的哑编码列,比如
drop_first=True后,列名应为Other_technologies_Javascript、Other_technologies_Kotlin、Other_technologies_Python、Other_technologies_SQL - 接收用户输入后,初始化一个全0的字典对应这些哑编码列
- 若用户选的不是参考组(
C/C++),则将对应列的值设为1
Flask后端示例代码
from flask import Flask, request, render_template import pandas as pd import joblib app = Flask(__name__) # 加载训练好的模型和预处理配置 model = joblib.load('rf_classifier.pkl') # 保存训练时生成的哑编码列(排除参考组) tech_dummy_cols = ['Other_technologies_Javascript', 'Other_technologies_Kotlin', 'Other_technologies_Python', 'Other_technologies_SQL'] reference_group = 'C/C++' @app.route('/', methods=['GET', 'POST']) def predict(): if request.method == 'POST': # 获取用户选择的技术 selected_tech = request.form.get('Other_technologies') # 初始化哑编码特征为全0 tech_features = {col: 0 for col in tech_dummy_cols} # 非参考组选项对应列设为1 if selected_tech != reference_group: target_col = f'Other_technologies_{selected_tech}' if target_col in tech_features: tech_features[target_col] = 1 # 整合其他预测变量(此处仅展示当前变量处理逻辑) input_df = pd.DataFrame([tech_features]) # 执行预测 result = model.predict(input_df)[0] return f"分类结果:{result}" return render_template('index.html') if __name__ == '__main__': app.run(debug=True)
3. 额外优化建议
- 若该变量支持多选(用户可同时选多个技术),前端可改用复选框(
<input type="checkbox" name="Other_technologies" value="Javascript">),后端处理时将所有选中项对应的哑编码列设为1即可 - 训练模型时,建议将哑编码的列名、参考组等配置信息单独保存(比如用
joblib存一个配置文件),避免后端硬编码列名,提升扩展性
内容的提问来源于stack exchange,提问作者Sweet Sveta
相关产品推荐
相关产品推荐

