from flask import Flask, request, jsonify, render_template import pandas as pd import joblib app = Flask(__name__) # 加载模型 model_path = "cardio_predictor_model.pkl" model = joblib.load(model_path) @app.route('/') def home(): return render_template('index.html') @app.route('/predict_cardio', methods=['POST']) def predict_cardio(): try: # 接收JSON请求数据 data = request.json # 验证输入特征数量 required_features = ['age', 'gender', 'height', 'weight', 'ap_hi', 'ap_lo', 'cholesterol', 'gluc', 'smoke', 'alco', 'active'] if not all(feature in data for feature in required_features): return jsonify({'error': '缺少必要的特征值'}), 400 # 转换为DataFrame input_data = pd.DataFrame([data]) # 执行与训练时相同的特征工程 input_data['age_years'] = round(input_data['age'] / 365.25, 0) input_data['bmi'] = input_data['weight'] / ((input_data['height'] / 100) ** 2) # 删除原始age字段 input_data = input_data.drop('age', axis=1) # 预测 probability = model.predict_proba(input_data)[0][1] prediction = int(model.predict(input_data)[0]) # 返回结果 response = { 'probability': float(probability), 'prediction': prediction } return jsonify(response) except Exception as e: return jsonify({'error': str(e)}), 500 if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000)