You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask部署LogisticRegression模型报错:输入特征数不符(1/30)

问题分析与解决方案

核心问题定位

报错ValueError: X has 1 features, but LogisticRegression is expecting 30 features as input明确说明:提交给模型的特征数量只有1个,而非模型要求的30个。同时代码中还存在未标准化输入、未定义y_prob变量两个隐藏问题。


分步解决方案

1. 修复表单数据提交问题

首先确保HTML表单能正确传递30个独立特征:

  • 检查index.html中的表单,确保有30个输入字段,每个字段的name属性唯一(避免重复或缺失),示例结构如下:
<form action="/predict" method="POST">
  {% for i in range(30) %}
    <div>
      <label>特征{{i+1}}:</label>
      <input type="number" name="feature{{i}}" step="any" required>
    </div>
  {% endfor %}
  <button type="submit">预测</button>
</form>
  • 在Flask的predict函数中添加特征数量校验,提前拦截错误:
features = [float(x) for x in request.form.values()]
# 验证特征数量
if len(features) != 30:
    return render_template('index.html', prediction_text=f"错误:需要30个特征,但仅收到{len(features)}个")

2. 修复模型输入处理逻辑

  • 移除多余的元组转换(列表可直接转为numpy数组)
  • 必须使用训练时保存的scaler对输入做标准化(训练和预测的预处理逻辑必须一致)
  • 补充y_prob变量的定义,通过predict_proba获取预测概率

修改后的predict函数:

@app.route('/predict',methods=['POST'])
def predict():
    features = [float(x) for x in request.form.values()]
    
    # 特征数量校验
    if len(features) != 30:
        return render_template('index.html', prediction_text=f"错误:需要30个特征,但仅收到{len(features)}个")
    
    # 转换为模型要求的格式并标准化
    input_data = np.asarray(features).reshape(1, -1)
    input_data_scaled = scaler.transform(input_data)
    
    # 预测类别与概率
    prediction = model.predict(input_data_scaled)
    y_prob = model.predict_proba(input_data_scaled)[0][prediction[0]]
    
    output = round(prediction[0], 2)
    
    if output == 0:
        return render_template('index.html', prediction_text=f'患者更可能患有良性癌症,概率值为 {round(y_prob, 4)}')
    else:
         return render_template('index.html', prediction_text=f'患者更可能患有恶性癌症,概率值为 {round(y_prob, 4)}')

3. 额外优化:API接口同步修复

对predict_api接口做同样的标准化和校验处理:

@app.route('/predict_api',methods=['POST'])
def predict_api():
    data = request.get_json(force=True)
    features = list(data.values())
    
    if len(features) != 30:
        return jsonify({"error": f"需要30个特征,但仅收到{len(features)}个"})
    
    input_data = np.array(features).reshape(1, -1)
    input_data_scaled = scaler.transform(input_data)
    
    prediction = model.predict(input_data_scaled)[0]
    y_prob = model.predict_proba(input_data_scaled)[0][prediction]
    
    return jsonify({
        "prediction": int(prediction),
        "probability": round(y_prob, 4),
        "result": "良性癌症" if prediction ==0 else "恶性癌症"
    })

4. 验证模型与scaler的正确性

确保model.pkl和scaler.pkl是训练时正确保存的:

# 训练阶段保存代码示例
pickle.dump(trained_model, open('model.pkl', 'wb'))
pickle.dump(trained_scaler, open('scaler.pkl', 'wb'))

内容的提问来源于stack exchange,提问作者Swastik Datta Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 21:29:58