diff --git a/src/routes.py b/src/routes.py index daa4fe4..0d2308e 100644 --- a/src/routes.py +++ b/src/routes.py @@ -107,39 +107,24 @@ def predict(): model_id = data.get('model_id') # 可选:指定模型ID logger.info(f"Received prediction request for equipment type: {equipment_type}") - # 获取可用模型(默认R²最高的;可选指定model_id) + # 获取最优模型(默认R²最高的;可选指定model_id) with get_db_connection() as conn: cursor = conn.cursor() if model_id: - cursor.execute(""" - SELECT * FROM trained_models - WHERE id = ? AND is_active = TRUE - """, (model_id,)) - models = cursor.fetchall() + cursor.execute("SELECT * FROM trained_models WHERE id = ? AND is_active = TRUE", (model_id,)) else: cursor.execute(""" SELECT * FROM trained_models - WHERE equipment_type = ? - AND model_type != 'pls' - AND is_active = TRUE - ORDER BY r2_score DESC + WHERE equipment_type = ? AND model_type != 'pls' AND is_active = TRUE + ORDER BY r2_score DESC LIMIT 1 """, (equipment_type,)) - models = cursor.fetchall() + model = cursor.fetchone() - if not models: - return jsonify({'error': '未找到可用的模型'}), 404 + if not model: + return jsonify({'error': '未找到可用的模型,请先训练'}), 404 - # 逐个尝试加载,跳过架构不兼容的模型 predictor = CostPredictor() - for model in models: - try: - prediction = predictor.predict(data, model) - break - except ValueError as e: - logger.warning(f"Model {model['model_name']} failed: {e}, trying next...") - continue - else: - return jsonify({'error': '所有激活模型加载失败,请重新训练'}), 500 + prediction = predictor.predict(data, model) # 返回预测结果 return jsonify({