Update code

This commit is contained in:
2026-04-02 19:52:38 +08:00
parent f77195a9d7
commit 9c040b3dec
15 changed files with 2100 additions and 1 deletions

View File

@@ -0,0 +1,13 @@
{
"permissions": {
"allow": [
"Bash(py:*)",
"Bash(python math.py)",
"Bash(git remote:*)",
"Bash(git config:*)",
"Bash(git add:*)",
"Bash(git commit:*)",
"Bash(git push:*)"
]
}
}

8
.idea/AIcode.iml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="D:\software\anaconda" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/AIcode.iml" filepath="$PROJECT_DIR$/.idea/AIcode.iml" />
</modules>
</component>
</project>

46
.idea/workspace.xml generated Normal file
View File

@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="c2fd381e-9b12-4d32-b4e8-24d694013b53" name="更改" comment="" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ProjectColorInfo"><![CDATA[{
"associatedIndex": 7
}]]></component>
<component name="ProjectId" id="3BmcLYQM9mcuqt9z3i5B1kZMOfO" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"ModuleVcsDetector.initialDetectionPerformed": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"nodejs_package_manager_path": "npm",
"settings.editor.selected.configurable": "preferences.lookFeel",
"vue.rearranger.settings.migration": "true"
}
}]]></component>
<component name="SharedIndexes">
<attachedChunks>
<set>
<option value="bundled-js-predefined-d6986cc7102b-6a121458b545-JavaScript-PY-251.25410.159" />
<option value="bundled-python-sdk-e0ed3721d81e-36ea0e71a18c-com.jetbrains.pycharm.pro.sharedIndexes.bundled-PY-251.25410.159" />
</set>
</attachedChunks>
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="默认任务">
<changelist id="c2fd381e-9b12-4d32-b4e8-24d694013b53" name="更改" comment="" />
<created>1775097630560</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1775097630560</updated>
<workItem from="1775097631689" duration="2000" />
</task>
<servers />
</component>
</project>

View File

@@ -4,7 +4,12 @@
"Bash(python -c \"import pandas as pd; df = pd.read_excel\\('data/心血管疾病.xlsx', nrows=5\\); print\\('Columns:', df.columns.tolist\\(\\)\\); print\\('Data types:', df.dtypes\\); print\\('Sample data:'\\); print\\(df.head\\(\\)\\)\")",
"Bash(\"D:\\\\software\\\\anaconda\\\\Scripts\\\\conda.exe\" run:*)",
"Bash(\"D:\\\\software\\\\anaconda\\\\envs\\\\cardioenv\\\\python.exe\" module1_dashboard/test_data.py)",
"Bash(\"D:\\\\software\\\\anaconda\\\\envs\\\\cardioenv\\\\python.exe\" -m streamlit run module1_dashboard/cardio_dashboard.py --help)"
"Bash(\"D:\\\\software\\\\anaconda\\\\envs\\\\cardioenv\\\\python.exe\" -m streamlit run module1_dashboard/cardio_dashboard.py --help)",
"Bash(\"D:\\\\software\\\\anaconda\\\\envs\\\\cardioenv\\\\python.exe\" -c \"import pandas as pd; df = pd.read_excel\\('data/心血管疾病.xlsx', nrows=10\\); print\\('Columns:', df.columns.tolist\\(\\)\\); print\\('\\\\nData types:'\\); print\\(df.dtypes\\); print\\('\\\\nSample data:'\\); print\\(df[['age', 'gender', 'height', 'weight', 'ap_hi', 'ap_lo', 'cholesterol', 'gluc', 'smoke', 'alco', 'active', 'cardio']].head\\(\\)\\)\")",
"Bash(\"D:\\\\software\\\\anaconda\\\\envs\\\\cardioenv\\\\python.exe\" -m py_compile module2_predictor/train_and_save.py)",
"Bash(\"D:\\\\software\\\\anaconda\\\\envs\\\\cardioenv\\\\python.exe\" module2_predictor/train_and_save.py)",
"Bash(\"D:\\\\software\\\\anaconda\\\\envs\\\\cardioenv\\\\python.exe\" -m py_compile module2_predictor/app.py)",
"Bash(\"D:\\\\software\\\\anaconda\\\\envs\\\\cardioenv\\\\python.exe\" module2_predictor/test_api.py)"
]
}
}

View File

@@ -156,6 +156,235 @@ MODEL_PATH=./module2_predictor/models/xgb_model.pkl
- **环境管理**: python-dotenv
- **AI集成**: langchain-openai, dashscope, requests
## Module 2: 机器学习预测器
### 功能特性
-**模型训练**: XGBoost分类器准确率约73%
-**特征工程**: 年龄转换、BMI计算、异常值处理
-**RESTful API**: Flask提供预测接口
-**前端界面**: 交互式Web表单实时预测
-**模型持久化**: Joblib保存完整Pipeline
### 模型训练
#### 1. 训练模型(一次性)
```bash
# 进入项目根目录
cd D:\Project\PythonProject\AIcode\test
# 激活conda环境
conda activate cardioenv
# 运行训练脚本
python module2_predictor/train_and_save.py
```
训练脚本将:
1. 加载和清洗数据与Module 1相同
2. 特征工程年龄转换、BMI计算
3. 构建机器学习PipelineStandardScaler + OneHotEncoder + XGBoost
4. 训练模型并评估性能
5. 保存模型到 `module2_predictor/models/cardio_predictor_model.pkl`
#### 2. 模型特征
- **连续特征**: age_years, bmi, ap_hi, ap_lo
- **分类特征**: gender, cholesterol, gluc
- **二元特征**: smoke, alco, active
**Top 5 重要特征**:
1. 收缩压 (ap_hi)
2. 极高胆固醇 (cholesterol_3)
3. 年龄 (age_years)
4. 舒张压 (ap_lo)
5. 极高血糖 (gluc_3)
### Flask API服务
#### 1. 启动API服务
```bash
# 进入项目根目录
cd D:\Project\PythonProject\AIcode\test
# 激活conda环境
conda activate cardioenv
# 方法1: 直接运行Python脚本
python module2_predictor/app.py
# 方法2: 使用Flask CLI
set FLASK_APP=module2_predictor/app.py
flask run --host=0.0.0.0 --port=5000
# 方法3: 使用conda直接运行
"D:\software\anaconda\Scripts\conda.exe" run -n cardioenv python module2_predictor/app.py
```
#### 2. API端点
| 端点 | 方法 | 描述 |
|------|------|------|
| `/` | GET | 前端预测界面 |
| `/predict_cardio` | POST | 预测接口接收JSON |
| `/health` | GET | 健康检查 |
| `/model_info` | GET | 模型信息 |
#### 3. 预测接口示例
**请求**:
```bash
curl -X POST http://localhost:5000/predict_cardio \
-H "Content-Type: application/json" \
-d '{
"age": 20228,
"gender": 1,
"height": 156,
"weight": 85,
"ap_hi": 140,
"ap_lo": 90,
"cholesterol": 1,
"gluc": 1,
"smoke": 0,
"alco": 0,
"active": 1
}'
```
**响应**:
```json
{
"success": true,
"prediction": 1,
"probability": 0.85,
"risk_level": "高危",
"message": "预测成功",
"features": {
"age_years": 55,
"bmi": 34.9,
"ap_hi": 140,
"ap_lo": 90,
"gender": 1,
"cholesterol": 1,
"gluc": 1,
"smoke": 0,
"alco": 0,
"active": 1
}
}
```
### 前端界面
访问 `http://localhost:5000` 使用预测界面:
1. **输入表单**: 11个特征字段包含验证和示例数据
2. **实时预测**: 点击"开始预测"获取风险评估
3. **结果展示**: 风险等级、概率、健康建议
4. **示例数据**: 提供低、中、高风险示例数据
### 项目结构
```
module2_predictor/
├── app.py # Flask应用主程序
├── train_and_save.py # 模型训练脚本(一次性)
├── test_api.py # API测试脚本
├── templates/
│ └── index.html # 前端界面模板
└── models/ # 模型文件目录(训练后生成)
├── cardio_predictor_model.pkl
└── feature_info.txt
```
### 测试验证
#### 1. 测试模型加载
```bash
python module2_predictor/test_api.py
```
#### 2. 测试API服务
1. 启动Flask应用`python module2_predictor/app.py`
2. 打开浏览器访问:`http://localhost:5000`
3. 使用示例数据测试预测功能
4. 检查健康状态:`http://localhost:5000/health`
#### 3. 验证预测准确性
- 测试集准确率约73%
- 特征重要性符合医学常识
- 风险等级划分合理
### 配置说明
#### 模型参数
- **算法**: XGBoost Classifier
- **树数量**: 100
- **最大深度**: 5
- **学习率**: 0.1
- **子采样率**: 0.8
- **随机种子**: 42
#### 特征预处理
- **连续特征**: StandardScaler标准化
- **分类特征**: OneHotEncoder独热编码
- **二元特征**: 直接使用0/1
### 性能指标
| 指标 | 训练集 | 测试集 |
|------|--------|--------|
| 准确率 | 74.21% | 73.14% |
| 特征数量 | 10个 | 10个 |
| 模型大小 | ~1.2 MB | ~1.2 MB |
### 注意事项
1. **模型更新**: 当数据变化时,重新运行训练脚本
2. **输入验证**: API对输入数据有严格的范围验证
3. **血压合理性**: 自动拒绝舒张压≥收缩压的输入
4. **错误处理**: 详细的错误信息和日志记录
5. **性能**: 单次预测时间 < 100ms
### 常见问题
#### Q1: 模型训练失败
**症状**: 训练脚本报错或无法保存模型
**解决**:
1. 检查数据文件路径是否正确
2. 确保有足够的磁盘空间
3. 检查Python依赖包是否完整安装
#### Q2: Flask应用无法启动
**症状**: 启动时出现导入错误或模型加载失败
**解决**:
1. 检查conda环境是否激活
2. 确保模型文件存在:`module2_predictor/models/cardio_predictor_model.pkl`
3. 检查端口5000是否被占用
#### Q3: 预测结果不合理
**症状**: 预测概率总是0或1或与预期不符
**解决**:
1. 检查输入数据是否在合理范围内
2. 验证特征预处理是否正确
3. 确保模型训练时使用了正确的特征
#### Q4: 前端界面无法访问
**症状**: 浏览器显示连接错误
**解决**:
1. 确认Flask应用正在运行
2. 检查防火墙设置允许端口5000
3. 尝试访问 `http://localhost:5000/health` 检查服务状态
### 下一步开发
1. **模型优化**: 尝试其他算法LightGBM, CatBoost和超参数调优
2. **特征扩展**: 添加更多临床特征(家族史、药物治疗等)
3. **API增强**: 添加批量预测、模型版本管理
4. **监控告警**: 添加性能监控和异常告警
5. **部署优化**: Docker容器化云平台部署
---
### 常见问题
#### Q1: 数据加载失败

Binary file not shown.

View File

@@ -0,0 +1,396 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
CardioAI - 心血管疾病预测API服务
功能:
1. 加载预训练的机器学习模型
2. 提供RESTful API接口
3. 接收原始特征值并返回预测结果
4. 提供Web前端界面
启动方式:
conda activate cardioenv
python app.py
flask run
"""
from flask import Flask, request, jsonify, render_template, send_from_directory
import pandas as pd
import numpy as np
import joblib
import logging
from pathlib import Path
import sys
import os
import traceback
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.append(str(project_root))
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# 创建Flask应用
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False # 确保JSON支持中文
# 全局变量存储模型和特征信息
model_data = None
feature_names = None
pipeline = None
def load_model():
"""加载预训练的模型"""
global model_data, feature_names, pipeline
try:
# 模型文件路径
model_dir = Path(__file__).parent / "models"
model_path = model_dir / "cardio_predictor_model.pkl"
if not model_path.exists():
logger.error(f"模型文件不存在: {model_path}")
raise FileNotFoundError(f"模型文件不存在: {model_path}")
# 加载模型
logger.info(f"正在加载模型: {model_path}")
model_data = joblib.load(model_path)
# 提取Pipeline和特征信息
pipeline = model_data['pipeline']
feature_names = model_data.get('feature_names', [])
logger.info(f"模型加载成功!版本: {model_data.get('model_version', '未知')}")
logger.info(f"特征数量: {len(feature_names)}")
logger.info(f"特征列表: {feature_names}")
return True
except Exception as e:
logger.error(f"模型加载失败: {str(e)}")
logger.error(traceback.format_exc())
return False
def preprocess_input(input_data):
"""
预处理输入数据(与训练时相同的处理)
参数:
input_data: 包含原始特征的字典
返回:
pd.DataFrame: 预处理后的特征数据框
"""
try:
# 创建数据框
df = pd.DataFrame([input_data])
# 1. 年龄转换:从天转换为年(四舍五入)
if 'age' in df.columns:
df['age_years'] = (df['age'] / 365.25).round().astype(int)
elif 'age_years' in df.columns:
# 如果已经提供了转换后的年龄,直接使用
df['age_years'] = df['age_years'].astype(int)
else:
raise ValueError("输入数据中必须包含'age''age_years'字段")
# 2. 计算BMI: BMI = weight(kg) / (height(m)^2)
if 'height' in df.columns and 'weight' in df.columns:
df['bmi'] = df['weight'] / ((df['height'] / 100) ** 2)
df['bmi'] = df['bmi'].round(2)
elif 'bmi' in df.columns:
# 如果已经提供了BMI直接使用
df['bmi'] = df['bmi'].astype(float)
else:
raise ValueError("输入数据中必须包含'height''weight'字段或'bmi'字段")
# 3. 确保所有必要特征都存在
required_features = ['age_years', 'bmi', 'ap_hi', 'ap_lo',
'gender', 'cholesterol', 'gluc',
'smoke', 'alco', 'active']
missing_features = [f for f in required_features if f not in df.columns]
if missing_features:
raise ValueError(f"缺少必要特征: {missing_features}")
# 4. 选择模型需要的特征(按训练时的顺序)
processed_df = df[required_features].copy()
logger.debug(f"预处理后的特征数据框:\n{processed_df}")
return processed_df
except Exception as e:
logger.error(f"数据预处理失败: {str(e)}")
raise
def validate_input(input_data):
"""
验证输入数据的有效性
参数:
input_data: 输入特征字典
返回:
tuple: (是否有效, 错误消息)
"""
try:
# 检查必需字段
required_fields = ['age', 'gender', 'height', 'weight',
'ap_hi', 'ap_lo', 'cholesterol', 'gluc',
'smoke', 'alco', 'active']
missing_fields = [f for f in required_fields if f not in input_data]
if missing_fields:
return False, f"缺少必需字段: {missing_fields}"
# 检查数据类型
for field in required_fields:
value = input_data[field]
if not isinstance(value, (int, float)):
try:
# 尝试转换为数值
input_data[field] = float(value)
except ValueError:
return False, f"字段'{field}'必须为数值类型,当前值: {value}"
# 检查数值范围
validations = [
('age', 0, 365*150), # 年龄0-150岁
('gender', 1, 2), # 性别1或2
('height', 100, 250), # 身高cm100-250
('weight', 20, 300), # 体重kg20-300
('ap_hi', 50, 300), # 收缩压50-300
('ap_lo', 30, 200), # 舒张压30-200
('cholesterol', 1, 3), # 胆固醇1-3
('gluc', 1, 3), # 血糖1-3
('smoke', 0, 1), # 吸烟0或1
('alco', 0, 1), # 饮酒0或1
('active', 0, 1) # 活动0或1
]
for field, min_val, max_val in validations:
value = input_data[field]
if not (min_val <= value <= max_val):
return False, f"字段'{field}'的值{value}超出有效范围[{min_val}, {max_val}]"
# 检查血压合理性
if input_data['ap_lo'] >= input_data['ap_hi']:
return False, "舒张压不能高于或等于收缩压"
return True, "输入数据有效"
except Exception as e:
return False, f"输入数据验证失败: {str(e)}"
@app.route('/')
def index():
"""主页 - 返回前端界面"""
return render_template('index.html')
@app.route('/predict_cardio', methods=['POST'])
def predict_cardio():
"""
心血管疾病预测API接口
请求格式JSON
{
"age": 20228, # 年龄(天)
"gender": 1, # 性别1=女性2=男性)
"height": 156, # 身高cm
"weight": 85, # 体重kg
"ap_hi": 140, # 收缩压mmHg
"ap_lo": 90, # 舒张压mmHg
"cholesterol": 1, # 胆固醇水平1=正常2=高于正常3=极高)
"gluc": 1, # 血糖水平1=正常2=高于正常3=极高)
"smoke": 0, # 吸烟0=否1=是)
"alco": 0, # 饮酒0=否1=是)
"active": 1 # 体育活动0=否1=是)
}
响应格式JSON
{
"success": true,
"prediction": 1,
"probability": 0.85,
"risk_level": "高危",
"message": "预测成功",
"features": {
"age_years": 55,
"bmi": 34.9,
... // 其他处理后的特征
}
}
"""
try:
# 检查模型是否已加载
if pipeline is None:
return jsonify({
"success": False,
"message": "模型未加载,请等待或联系管理员"
}), 503
# 获取JSON数据
if not request.is_json:
return jsonify({
"success": False,
"message": "请求必须是JSON格式"
}), 400
input_data = request.get_json()
logger.info(f"收到预测请求: {input_data}")
# 验证输入数据
is_valid, error_message = validate_input(input_data)
if not is_valid:
return jsonify({
"success": False,
"message": error_message
}), 400
# 预处理输入数据
processed_df = preprocess_input(input_data)
# 进行预测
prediction = pipeline.predict(processed_df)[0]
probability = pipeline.predict_proba(processed_df)[0][1] # 类别1的概率
# 确定风险等级
if probability < 0.3:
risk_level = "低危"
elif probability < 0.6:
risk_level = "中危"
else:
risk_level = "高危"
# 准备响应数据
response_data = {
"success": True,
"prediction": int(prediction),
"probability": float(round(probability, 4)),
"risk_level": risk_level,
"message": "预测成功",
"features": {
"age_years": int(processed_df['age_years'].iloc[0]),
"bmi": float(round(processed_df['bmi'].iloc[0], 2)),
"ap_hi": int(processed_df['ap_hi'].iloc[0]),
"ap_lo": int(processed_df['ap_lo'].iloc[0]),
"gender": int(processed_df['gender'].iloc[0]),
"cholesterol": int(processed_df['cholesterol'].iloc[0]),
"gluc": int(processed_df['gluc'].iloc[0]),
"smoke": int(processed_df['smoke'].iloc[0]),
"alco": int(processed_df['alco'].iloc[0]),
"active": int(processed_df['active'].iloc[0])
}
}
logger.info(f"预测结果: {response_data}")
return jsonify(response_data), 200
except Exception as e:
error_msg = f"预测过程中发生错误: {str(e)}"
logger.error(error_msg)
logger.error(traceback.format_exc())
return jsonify({
"success": False,
"message": error_msg
}), 500
@app.route('/health', methods=['GET'])
def health_check():
"""健康检查端点"""
try:
if pipeline is None:
return jsonify({
"status": "unhealthy",
"message": "模型未加载"
}), 503
# 简单的模型测试
test_data = {
"age": 20228,
"gender": 1,
"height": 156,
"weight": 85,
"ap_hi": 140,
"ap_lo": 90,
"cholesterol": 1,
"gluc": 1,
"smoke": 0,
"alco": 0,
"active": 1
}
processed_df = preprocess_input(test_data)
_ = pipeline.predict(processed_df)
return jsonify({
"status": "healthy",
"model_version": model_data.get('model_version', '未知'),
"features": len(feature_names) if feature_names else 0,
"message": "模型服务运行正常"
}), 200
except Exception as e:
return jsonify({
"status": "unhealthy",
"message": f"健康检查失败: {str(e)}"
}), 500
@app.route('/model_info', methods=['GET'])
def model_info():
"""获取模型信息"""
if model_data is None:
return jsonify({
"success": False,
"message": "模型未加载"
}), 503
return jsonify({
"success": True,
"model_version": model_data.get('model_version', '未知'),
"description": model_data.get('description', 'CardioAI心血管疾病预测模型'),
"feature_count": len(feature_names) if feature_names else 0,
"features": feature_names if feature_names else []
}), 200
# 模型加载标志
_model_loaded = False
@app.before_request
def ensure_model_loaded():
"""确保模型已加载(每个请求前检查)"""
global pipeline, model_data, feature_names, _model_loaded
if not _model_loaded:
logger.info("首次请求,正在加载模型...")
success = load_model()
if success:
_model_loaded = True
logger.info("模型加载完成")
else:
logger.error("模型加载失败")
if __name__ == '__main__':
# 加载模型
success = load_model()
if not success:
logger.error("启动失败: 模型加载失败")
sys.exit(1)
# 启动Flask应用
logger.info("启动CardioAI预测API服务...")
logger.info("访问 http://localhost:5000 使用预测界面")
logger.info("API文档:")
logger.info(" GET / - 前端界面")
logger.info(" POST /predict_cardio - 预测接口")
logger.info(" GET /health - 健康检查")
logger.info(" GET /model_info - 模型信息")
app.run(host='0.0.0.0', port=5000, debug=True)

View File

@@ -0,0 +1,27 @@
CardioAI模型特征信息
==================================================
特征列表(按输入顺序):
1. age_years
2. bmi
3. ap_hi
4. ap_lo
5. gender
6. cholesterol
7. gluc
8. smoke
9. alco
10. active
特征说明:
- age_years: 年龄(岁),由原始天数转换而来
- bmi: 身体质量指数,计算公式:体重(kg) / (身高(m)^2)
- ap_hi: 收缩压mmHg
- ap_lo: 舒张压mmHg
- gender: 性别1=女性2=男性)
- cholesterol: 胆固醇水平1=正常2=高于正常3=极高)
- gluc: 血糖水平1=正常2=高于正常3=极高)
- smoke: 吸烟0=否1=是)
- alco: 饮酒0=否1=是)
- active: 体育活动0=否1=是)

View File

@@ -0,0 +1,858 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CardioAI - 心血管疾病风险预测</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root {
--primary-color: #e63946;
--secondary-color: #457b9d;
--success-color: #2a9d8f;
--warning-color: #e9c46a;
--danger-color: #e63946;
--light-color: #f1faee;
--dark-color: #1d3557;
}
body {
font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
min-height: 100vh;
padding-bottom: 50px;
}
.navbar {
background: linear-gradient(to right, var(--dark-color), var(--secondary-color));
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.navbar-brand {
font-weight: bold;
font-size: 1.5rem;
color: white !important;
}
.card {
border: none;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
margin-bottom: 20px;
}
.card:hover {
transform: translateY(-5px);
}
.card-header {
background: linear-gradient(to right, var(--secondary-color), var(--dark-color));
color: white;
border-radius: 15px 15px 0 0 !important;
font-weight: bold;
padding: 15px 20px;
}
.form-control, .form-select {
border-radius: 8px;
border: 1px solid #ddd;
padding: 10px 15px;
transition: all 0.3s;
}
.form-control:focus, .form-select:focus {
border-color: var(--secondary-color);
box-shadow: 0 0 0 0.25rem rgba(69, 123, 157, 0.25);
}
.btn-primary {
background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
border: none;
border-radius: 8px;
padding: 12px 30px;
font-weight: bold;
transition: all 0.3s;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(230, 57, 70, 0.3);
}
.btn-secondary {
background: linear-gradient(to right, var(--dark-color), #2c3e50);
border: none;
border-radius: 8px;
padding: 12px 30px;
font-weight: bold;
transition: all 0.3s;
}
.btn-secondary:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(29, 53, 87, 0.3);
}
.result-card {
border-left: 5px solid var(--secondary-color);
}
.risk-low {
color: var(--success-color);
font-weight: bold;
}
.risk-medium {
color: var(--warning-color);
font-weight: bold;
}
.risk-high {
color: var(--danger-color);
font-weight: bold;
}
.feature-value {
background-color: var(--light-color);
padding: 5px 10px;
border-radius: 5px;
font-family: monospace;
font-weight: bold;
}
.loading {
display: none;
text-align: center;
padding: 20px;
}
.spinner {
width: 3rem;
height: 3rem;
border-width: 0.3em;
}
.alert {
border-radius: 10px;
border: none;
}
.feature-group {
margin-bottom: 15px;
}
.feature-label {
font-weight: 600;
margin-bottom: 5px;
color: var(--dark-color);
}
.help-text {
font-size: 0.85rem;
color: #6c757d;
margin-top: 3px;
}
footer {
background-color: var(--dark-color);
color: white;
padding: 20px 0;
margin-top: 40px;
border-radius: 15px 15px 0 0;
}
.heart-icon {
color: var(--primary-color);
animation: heartbeat 1.5s infinite;
}
@keyframes heartbeat {
0% { transform: scale(1); }
5% { transform: scale(1.1); }
10% { transform: scale(1); }
15% { transform: scale(1.1); }
20% { transform: scale(1); }
100% { transform: scale(1); }
}
.tooltip-inner {
max-width: 300px;
text-align: left;
}
</style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark">
<div class="container">
<a class="navbar-brand" href="#">
<i class="fas fa-heartbeat me-2 heart-icon"></i>
CardioAI - 心血管疾病风险预测系统
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link active" href="#"><i class="fas fa-home me-1"></i> 首页</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/health" target="_blank"><i class="fas fa-heart me-1"></i> 服务状态</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/model_info" target="_blank"><i class="fas fa-info-circle me-1"></i> 模型信息</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- 主内容区 -->
<div class="container mt-4">
<div class="row">
<!-- 左侧:输入表单 -->
<div class="col-lg-6">
<div class="card">
<div class="card-header">
<i class="fas fa-clipboard-list me-2"></i> 患者基本信息输入
</div>
<div class="card-body">
<form id="predictionForm">
<!-- 年龄 -->
<div class="feature-group">
<label class="feature-label" for="age">
<i class="fas fa-birthday-cake me-1"></i> 年龄(天)
</label>
<input type="number" class="form-control" id="age" name="age"
placeholder="请输入年龄(天数)" min="0" max="36500" required
data-bs-toggle="tooltip" data-bs-placement="top"
title="输入年龄单位为天。例如55岁 = 55 × 365 = 20075天">
<div class="help-text">示例55岁 ≈ 20075天</div>
</div>
<!-- 性别 -->
<div class="feature-group">
<label class="feature-label" for="gender">
<i class="fas fa-venus-mars me-1"></i> 性别
</label>
<select class="form-select" id="gender" name="gender" required>
<option value="">请选择性别</option>
<option value="1">女性</option>
<option value="2">男性</option>
</select>
<div class="help-text">1=女性2=男性</div>
</div>
<div class="row">
<!-- 身高 -->
<div class="col-md-6">
<div class="feature-group">
<label class="feature-label" for="height">
<i class="fas fa-ruler-vertical me-1"></i> 身高cm
</label>
<input type="number" class="form-control" id="height" name="height"
placeholder="身高(厘米)" min="100" max="250" required>
<div class="help-text">范围100-250 cm</div>
</div>
</div>
<!-- 体重 -->
<div class="col-md-6">
<div class="feature-group">
<label class="feature-label" for="weight">
<i class="fas fa-weight me-1"></i> 体重kg
</label>
<input type="number" class="form-control" id="weight" name="weight"
placeholder="体重(千克)" min="20" max="300" required>
<div class="help-text">范围20-300 kg</div>
</div>
</div>
</div>
<div class="row">
<!-- 收缩压 -->
<div class="col-md-6">
<div class="feature-group">
<label class="feature-label" for="ap_hi">
<i class="fas fa-tachometer-alt me-1"></i> 收缩压mmHg
</label>
<input type="number" class="form-control" id="ap_hi" name="ap_hi"
placeholder="收缩压" min="50" max="300" required>
<div class="help-text">范围50-300 mmHg</div>
</div>
</div>
<!-- 舒张压 -->
<div class="col-md-6">
<div class="feature-group">
<label class="feature-label" for="ap_lo">
<i class="fas fa-tachometer-alt me-1"></i> 舒张压mmHg
</label>
<input type="number" class="form-control" id="ap_lo" name="ap_lo"
placeholder="舒张压" min="30" max="200" required>
<div class="help-text">范围30-200 mmHg</div>
</div>
</div>
</div>
<!-- 胆固醇水平 -->
<div class="feature-group">
<label class="feature-label" for="cholesterol">
<i class="fas fa-vial me-1"></i> 胆固醇水平
</label>
<select class="form-select" id="cholesterol" name="cholesterol" required>
<option value="">请选择胆固醇水平</option>
<option value="1">正常</option>
<option value="2">高于正常</option>
<option value="3">极高</option>
</select>
<div class="help-text">1=正常2=高于正常3=极高</div>
</div>
<!-- 血糖水平 -->
<div class="feature-group">
<label class="feature-label" for="gluc">
<i class="fas fa-vial me-1"></i> 血糖水平
</label>
<select class="form-select" id="gluc" name="gluc" required>
<option value="">请选择血糖水平</option>
<option value="1">正常</option>
<option value="2">高于正常</option>
<option value="3">极高</option>
</select>
<div class="help-text">1=正常2=高于正常3=极高</div>
</div>
<!-- 生活方式 -->
<div class="row">
<div class="col-md-4">
<div class="feature-group">
<label class="feature-label" for="smoke">
<i class="fas fa-smoking me-1"></i> 吸烟
</label>
<select class="form-select" id="smoke" name="smoke" required>
<option value="0"></option>
<option value="1"></option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="feature-group">
<label class="feature-label" for="alco">
<i class="fas fa-wine-glass-alt me-1"></i> 饮酒
</label>
<select class="form-select" id="alco" name="alco" required>
<option value="0"></option>
<option value="1"></option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="feature-group">
<label class="feature-label" for="active">
<i class="fas fa-running me-1"></i> 体育活动
</label>
<select class="form-select" id="active" name="active" required>
<option value="0"></option>
<option value="1"></option>
</select>
</div>
</div>
</div>
<!-- 按钮组 -->
<div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
<button type="button" class="btn btn-secondary me-md-2" id="btnReset">
<i class="fas fa-redo me-1"></i> 重置表单
</button>
<button type="submit" class="btn btn-primary" id="btnPredict">
<i class="fas fa-stethoscope me-1"></i> 开始预测
</button>
</div>
</form>
<!-- 加载动画 -->
<div class="loading mt-4" id="loading">
<div class="spinner-border text-primary spinner" role="status">
<span class="visually-hidden">加载中...</span>
</div>
<p class="mt-3">正在分析数据,请稍候...</p>
</div>
</div>
</div>
<!-- 示例数据卡片 -->
<div class="card">
<div class="card-header">
<i class="fas fa-lightbulb me-2"></i> 示例数据
</div>
<div class="card-body">
<p class="card-text">点击下方按钮填充示例数据:</p>
<div class="d-grid gap-2">
<button type="button" class="btn btn-outline-primary" id="btnExampleLow">
<i class="fas fa-user-check me-1"></i> 低风险示例
</button>
<button type="button" class="btn btn-outline-warning" id="btnExampleMedium">
<i class="fas fa-user me-1"></i> 中风险示例
</button>
<button type="button" class="btn btn-outline-danger" id="btnExampleHigh">
<i class="fas fa-user-injured me-1"></i> 高风险示例
</button>
</div>
</div>
</div>
</div>
<!-- 右侧:结果显示 -->
<div class="col-lg-6">
<div class="card result-card">
<div class="card-header">
<i class="fas fa-chart-line me-2"></i> 预测结果分析
</div>
<div class="card-body">
<div id="resultPlaceholder" class="text-center">
<i class="fas fa-chart-bar fa-4x text-muted mb-3"></i>
<h5 class="text-muted">等待预测结果</h5>
<p class="text-muted">填写左侧表单并点击"开始预测"按钮,系统将分析您的心血管疾病风险。</p>
</div>
<div id="resultContent" style="display: none;">
<!-- 风险等级 -->
<div class="alert" id="riskAlert">
<h4 class="alert-heading" id="riskTitle"></h4>
<p id="riskDescription"></p>
<hr>
<p class="mb-0" id="riskRecommendation"></p>
</div>
<!-- 预测结果详情 -->
<div class="mt-4">
<h5><i class="fas fa-info-circle me-2"></i> 预测详情</h5>
<table class="table table-borderless">
<tr>
<th width="40%">预测结果:</th>
<td><span class="badge bg-primary" id="predictionResult"></span></td>
</tr>
<tr>
<th>患病概率:</th>
<td><span class="feature-value" id="probabilityValue"></span></td>
</tr>
<tr>
<th>风险等级:</th>
<td><span id="riskLevel"></span></td>
</tr>
<tr>
<th>处理后的年龄:</th>
<td><span class="feature-value" id="ageYears"></span></td>
</tr>
<tr>
<th>身体质量指数BMI</th>
<td><span class="feature-value" id="bmiValue"></span></td>
</tr>
</table>
</div>
<!-- 特征总结 -->
<div class="mt-4">
<h5><i class="fas fa-list-ul me-2"></i> 输入特征总结</h5>
<div class="row" id="featureSummary">
<!-- 特征将通过JavaScript动态填充 -->
</div>
</div>
<!-- 行动建议 -->
<div class="alert alert-info mt-4">
<h5><i class="fas fa-hands-helping me-2"></i> 健康建议</h5>
<ul id="healthAdvice">
<!-- 建议将通过JavaScript动态填充 -->
</ul>
</div>
</div>
</div>
</div>
<!-- 系统信息 -->
<div class="card">
<div class="card-header">
<i class="fas fa-cogs me-2"></i> 系统信息
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<p><strong><i class="fas fa-server me-2"></i> 服务状态:</strong>
<span class="badge bg-success" id="serviceStatus">正常</span>
</p>
<p><strong><i class="fas fa-brain me-2"></i> 预测模型:</strong>
<span id="modelName">CardioAI XGBoost</span>
</p>
</div>
<div class="col-md-6">
<p><strong><i class="fas fa-history me-2"></i> 响应时间:</strong>
<span id="responseTime">--</span> ms
</p>
<p><strong><i class="fas fa-calendar-alt me-2"></i> 最后更新:</strong>
<span id="lastUpdate">2024-04-02</span>
</p>
</div>
</div>
<div class="d-grid gap-2 d-md-flex justify-content-md-end mt-2">
<button class="btn btn-sm btn-outline-secondary" id="btnRefreshStatus">
<i class="fas fa-sync-alt me-1"></i> 刷新状态
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 页脚 -->
<footer>
<div class="container text-center">
<p class="mb-2">
<i class="fas fa-heartbeat me-2 heart-icon"></i>
CardioAI - 心血管疾病智能辅助系统 v1.0
</p>
<p class="small mb-0">
本系统基于机器学习模型提供风险评估,结果仅供参考,不能替代专业医疗诊断。
<br>
如有健康问题,请及时咨询专业医生。
</p>
</div>
</footer>
<!-- Bootstrap JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- 自定义JavaScript -->
<script>
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
// 初始化工具提示
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl);
});
// 检查服务状态
checkServiceStatus();
// 绑定事件
document.getElementById('predictionForm').addEventListener('submit', handlePrediction);
document.getElementById('btnReset').addEventListener('click', resetForm);
document.getElementById('btnRefreshStatus').addEventListener('click', checkServiceStatus);
// 示例数据按钮
document.getElementById('btnExampleLow').addEventListener('click', () => fillExampleData('low'));
document.getElementById('btnExampleMedium').addEventListener('click', () => fillExampleData('medium'));
document.getElementById('btnExampleHigh').addEventListener('click', () => fillExampleData('high'));
// 初始填充低风险示例
setTimeout(() => fillExampleData('low'), 500);
});
// 检查服务状态
async function checkServiceStatus() {
try {
const response = await fetch('/health');
const data = await response.json();
if (data.status === 'healthy') {
document.getElementById('serviceStatus').className = 'badge bg-success';
document.getElementById('serviceStatus').textContent = '正常';
document.getElementById('modelName').textContent = data.model_version || 'CardioAI XGBoost';
} else {
document.getElementById('serviceStatus').className = 'badge bg-danger';
document.getElementById('serviceStatus').textContent = '异常';
}
} catch (error) {
console.error('服务状态检查失败:', error);
document.getElementById('serviceStatus').className = 'badge bg-danger';
document.getElementById('serviceStatus').textContent = '连接失败';
}
}
// 处理预测表单提交
async function handlePrediction(event) {
event.preventDefault();
// 显示加载动画
document.getElementById('loading').style.display = 'block';
document.getElementById('btnPredict').disabled = true;
// 收集表单数据
const formData = {
age: parseInt(document.getElementById('age').value),
gender: parseInt(document.getElementById('gender').value),
height: parseInt(document.getElementById('height').value),
weight: parseInt(document.getElementById('weight').value),
ap_hi: parseInt(document.getElementById('ap_hi').value),
ap_lo: parseInt(document.getElementById('ap_lo').value),
cholesterol: parseInt(document.getElementById('cholesterol').value),
gluc: parseInt(document.getElementById('gluc').value),
smoke: parseInt(document.getElementById('smoke').value),
alco: parseInt(document.getElementById('alco').value),
active: parseInt(document.getElementById('active').value)
};
// 验证血压
if (formData.ap_lo >= formData.ap_hi) {
alert('错误:舒张压不能高于或等于收缩压');
document.getElementById('loading').style.display = 'none';
document.getElementById('btnPredict').disabled = false;
return;
}
try {
const startTime = Date.now();
// 发送预测请求
const response = await fetch('/predict_cardio', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData)
});
const responseTime = Date.now() - startTime;
document.getElementById('responseTime').textContent = responseTime;
const data = await response.json();
// 隐藏加载动画
document.getElementById('loading').style.display = 'none';
document.getElementById('btnPredict').disabled = false;
if (data.success) {
// 显示结果
displayPredictionResult(data);
} else {
alert('预测失败:' + data.message);
}
} catch (error) {
console.error('预测请求失败:', error);
document.getElementById('loading').style.display = 'none';
document.getElementById('btnPredict').disabled = false;
alert('网络请求失败,请检查服务器状态');
}
}
// 显示预测结果
function displayPredictionResult(data) {
// 隐藏占位符,显示结果内容
document.getElementById('resultPlaceholder').style.display = 'none';
document.getElementById('resultContent').style.display = 'block';
// 更新预测结果
const predictionText = data.prediction === 1 ? '有心血管疾病风险' : '无心血管疾病风险';
document.getElementById('predictionResult').textContent = predictionText;
// 更新概率
const probabilityPercent = (data.probability * 100).toFixed(1);
document.getElementById('probabilityValue').textContent = `${probabilityPercent}%`;
// 更新风险等级
let riskClass = '';
let riskIcon = '';
if (data.risk_level === '低危') {
riskClass = 'risk-low';
riskIcon = 'fa-smile';
} else if (data.risk_level === '中危') {
riskClass = 'risk-medium';
riskIcon = 'fa-meh';
} else {
riskClass = 'risk-high';
riskIcon = 'fa-frown';
}
document.getElementById('riskLevel').innerHTML =
`<i class="fas ${riskIcon} me-1"></i><span class="${riskClass}">${data.risk_level}</span>`;
// 更新风险警告框
const alertElement = document.getElementById('riskAlert');
if (data.risk_level === '低危') {
alertElement.className = 'alert alert-success';
alertElement.innerHTML = `
<h4 class="alert-heading"><i class="fas fa-thumbs-up me-2"></i> 低风险</h4>
<p>根据模型分析,您当前的心血管疾病风险较低。继续保持健康的生活方式!</p>
<hr>
<p class="mb-0">建议定期进行健康检查,维持当前的健康状态。</p>
`;
} else if (data.risk_level === '中危') {
alertElement.className = 'alert alert-warning';
alertElement.innerHTML = `
<h4 class="alert-heading"><i class="fas fa-exclamation-triangle me-2"></i> 中风险</h4>
<p>根据模型分析,您有一定的心血管疾病风险,建议关注相关健康指标。</p>
<hr>
<p class="mb-0">建议改善生活方式,并考虑进行更详细的医学检查。</p>
`;
} else {
alertElement.className = 'alert alert-danger';
alertElement.innerHTML = `
<h4 class="alert-heading"><i class="fas fa-exclamation-circle me-2"></i> 高风险</h4>
<p>根据模型分析,您的心血管疾病风险较高,建议尽快咨询专业医生。</p>
<hr>
<p class="mb-0">请及时就医,进行全面的心血管健康评估。</p>
`;
}
// 更新处理后的特征
document.getElementById('ageYears').textContent = data.features.age_years;
document.getElementById('bmiValue').textContent = data.features.bmi;
// 更新特征总结
const featureSummary = document.getElementById('featureSummary');
featureSummary.innerHTML = `
<div class="col-md-6">
<p><strong>年龄:</strong> ${data.features.age_years} 岁</p>
<p><strong>性别:</strong> ${data.features.gender === 1 ? '女性' : '男性'}</p>
<p><strong>BMI</strong> ${data.features.bmi}</p>
<p><strong>血压:</strong> ${data.features.ap_hi}/${data.features.ap_lo} mmHg</p>
</div>
<div class="col-md-6">
<p><strong>胆固醇:</strong> ${getCholesterolText(data.features.cholesterol)}</p>
<p><strong>血糖:</strong> ${getGlucText(data.features.gluc)}</p>
<p><strong>吸烟:</strong> ${data.features.smoke === 1 ? '是' : '否'}</p>
<p><strong>饮酒:</strong> ${data.features.alco === 1 ? '是' : '否'}</p>
<p><strong>体育活动:</strong> ${data.features.active === 1 ? '是' : '否'}</p>
</div>
`;
// 更新健康建议
const healthAdvice = document.getElementById('healthAdvice');
let adviceItems = [];
if (data.features.bmi > 25) {
adviceItems.push('<li>您的BMI偏高建议控制体重保持健康饮食</li>');
}
if (data.features.ap_hi > 140 || data.features.ap_lo > 90) {
adviceItems.push('<li>您的血压偏高,建议定期监测血压,减少盐分摄入</li>');
}
if (data.features.cholesterol > 1) {
adviceItems.push('<li>您的胆固醇水平偏高,建议减少高胆固醇食物摄入</li>');
}
if (data.features.gluc > 1) {
adviceItems.push('<li>您的血糖水平偏高,建议控制糖分摄入,定期监测血糖</li>');
}
if (data.features.smoke === 1) {
adviceItems.push('<li>吸烟是心血管疾病的重要风险因素,建议戒烟</li>');
}
if (data.features.active === 0) {
adviceItems.push('<li>缺乏体育活动建议每周进行至少150分钟的中等强度运动</li>');
}
if (adviceItems.length === 0) {
adviceItems.push('<li>保持当前健康的生活方式,定期进行体检</li>');
}
healthAdvice.innerHTML = adviceItems.join('');
}
// 重置表单
function resetForm() {
document.getElementById('predictionForm').reset();
document.getElementById('resultPlaceholder').style.display = 'block';
document.getElementById('resultContent').style.display = 'none';
}
// 填充示例数据
function fillExampleData(type) {
let exampleData;
switch(type) {
case 'low':
exampleData = {
age: 18000, // 约49岁
gender: 1, // 女性
height: 165,
weight: 60,
ap_hi: 120,
ap_lo: 80,
cholesterol: 1,
gluc: 1,
smoke: 0,
alco: 0,
active: 1
};
break;
case 'medium':
exampleData = {
age: 25000, // 约68岁
gender: 2, // 男性
height: 170,
weight: 80,
ap_hi: 140,
ap_lo: 90,
cholesterol: 2,
gluc: 1,
smoke: 1,
alco: 1,
active: 0
};
break;
case 'high':
exampleData = {
age: 30000, // 约82岁
gender: 2, // 男性
height: 168,
weight: 95,
ap_hi: 160,
ap_lo: 100,
cholesterol: 3,
gluc: 2,
smoke: 1,
alco: 1,
active: 0
};
break;
}
// 填充表单
for (const [key, value] of Object.entries(exampleData)) {
const element = document.getElementById(key);
if (element) {
element.value = value;
}
}
// 重置结果显示
document.getElementById('resultPlaceholder').style.display = 'block';
document.getElementById('resultContent').style.display = 'none';
}
// 辅助函数:获取胆固醇文本描述
function getCholesterolText(value) {
switch(value) {
case 1: return '正常';
case 2: return '高于正常';
case 3: return '极高';
default: return '未知';
}
}
// 辅助函数:获取血糖文本描述
function getGlucText(value) {
switch(value) {
case 1: return '正常';
case 2: return '高于正常';
case 3: return '极高';
default: return '未知';
}
}
</script>
</body>
</html>

View File

@@ -0,0 +1,172 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
CardioAI API测试脚本
测试模型加载和预测功能
"""
import sys
import os
import json
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.append(str(project_root))
# 导入Flask应用中的函数
from app import load_model, preprocess_input
def test_model_loading():
"""测试模型加载"""
print("测试模型加载...")
try:
success = load_model()
if success:
print("✅ 模型加载成功")
return True
else:
print("❌ 模型加载失败")
return False
except Exception as e:
print(f"❌ 模型加载异常: {str(e)}")
return False
def test_data_preprocessing():
"""测试数据预处理"""
print("\n测试数据预处理...")
# 测试数据
test_data = {
"age": 20228, # 约55岁
"gender": 1, # 女性
"height": 156, # 身高cm
"weight": 85, # 体重kg
"ap_hi": 140, # 收缩压mmHg
"ap_lo": 90, # 舒张压mmHg
"cholesterol": 1, # 胆固醇水平
"gluc": 1, # 血糖水平
"smoke": 0, # 吸烟
"alco": 0, # 饮酒
"active": 1 # 体育活动
}
try:
processed_df = preprocess_input(test_data)
print(f"✅ 数据预处理成功")
print(f" 处理后的特征:")
for col in processed_df.columns:
print(f" {col}: {processed_df[col].iloc[0]}")
return True
except Exception as e:
print(f"❌ 数据预处理失败: {str(e)}")
return False
def test_prediction():
"""测试预测功能"""
print("\n测试预测功能...")
# 需要导入pipeline
from app import pipeline
if pipeline is None:
print("❌ 模型未加载,无法测试预测")
return False
# 测试数据
test_data = {
"age": 20228,
"gender": 1,
"height": 156,
"weight": 85,
"ap_hi": 140,
"ap_lo": 90,
"cholesterol": 1,
"gluc": 1,
"smoke": 0,
"alco": 0,
"active": 1
}
try:
processed_df = preprocess_input(test_data)
prediction = pipeline.predict(processed_df)[0]
probability = pipeline.predict_proba(processed_df)[0][1]
print(f"✅ 预测成功")
print(f" 预测结果: {prediction} ({'有风险' if prediction == 1 else '无风险'})")
print(f" 患病概率: {probability:.4f} ({(probability*100):.1f}%)")
# 确定风险等级
if probability < 0.3:
risk_level = "低危"
elif probability < 0.6:
risk_level = "中危"
else:
risk_level = "高危"
print(f" 风险等级: {risk_level}")
return True
except Exception as e:
print(f"❌ 预测失败: {str(e)}")
import traceback
traceback.print_exc()
return False
def test_api_endpoint():
"""测试API端点需要启动服务器"""
print("\n测试API端点...")
print("注意此测试需要Flask服务器正在运行")
print("请先启动Flask应用然后运行此测试")
# 这里可以添加实际的HTTP请求测试
# 但为了简单起见,我们只是提示用户
print("使用以下命令启动服务器:")
print(' cd "D:\\Project\\PythonProject\\AIcode\\test"')
print(' "D:\\software\\anaconda\\envs\\cardioenv\\python.exe" module2_predictor/app.py')
print("\n然后使用curl或浏览器测试API:")
print(' curl -X POST http://localhost:5000/predict_cardio \\')
print(' -H "Content-Type: application/json" \\')
print(' -d \'{"age":20228,"gender":1,"height":156,"weight":85,"ap_hi":140,"ap_lo":90,"cholesterol":1,"gluc":1,"smoke":0,"alco":0,"active":1}\'')
def main():
"""主测试函数"""
print("=" * 60)
print("CardioAI API 测试")
print("=" * 60)
# 测试模型加载
model_loaded = test_model_loading()
if model_loaded:
# 测试数据预处理
preprocessing_ok = test_data_preprocessing()
# 测试预测功能
prediction_ok = test_prediction()
# 汇总结果
print("\n" + "=" * 60)
print("测试结果汇总:")
print(f" 模型加载: {'✅ 通过' if model_loaded else '❌ 失败'}")
print(f" 数据预处理: {'✅ 通过' if preprocessing_ok else '❌ 失败'}")
print(f" 预测功能: {'✅ 通过' if prediction_ok else '❌ 失败'}")
if model_loaded and preprocessing_ok and prediction_ok:
print("\n🎉 所有测试通过!")
print("Flask API可以正常运行。")
return True
else:
print("\n⚠️ 部分测试失败,请检查问题。")
return False
else:
print("\n❌ 模型加载失败,无法继续测试。")
return False
# 显示API测试说明
test_api_endpoint()
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)

View File

@@ -0,0 +1,331 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
CardioAI - 心血管疾病预测模型训练脚本
功能:
1. 加载和清洗数据与模块1相同的流程
2. 特征工程年龄转换、BMI计算、异常值处理
3. 构建机器学习Pipeline
4. 训练XGBoost分类器
5. 保存完整Pipeline到文件
注意此脚本为一次性训练脚本生成模型文件供Flask应用使用。
"""
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from xgboost import XGBClassifier
import joblib
import warnings
import sys
import os
from pathlib import Path
# 忽略警告
warnings.filterwarnings('ignore')
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.append(str(project_root))
def load_and_preprocess_data():
"""
加载数据并进行预处理与模块1相同的清洗和特征工程
返回:
pd.DataFrame: 预处理后的数据框
"""
print("开始加载和预处理数据...")
# 数据文件路径
data_path = project_root / "data" / "心血管疾病.xlsx"
try:
# 加载数据
df = pd.read_excel(data_path)
print(f"原始数据形状: {df.shape}")
# 检查必要列
required_columns = ['id', 'age', 'gender', 'height', 'weight', 'ap_hi', 'ap_lo',
'cholesterol', 'gluc', 'smoke', 'alco', 'active', 'cardio']
missing_columns = [col for col in required_columns if col not in df.columns]
if missing_columns:
raise ValueError(f"数据文件中缺少必要列: {missing_columns}")
# 创建数据副本
df_processed = df.copy()
# 1. 年龄转换:从天转换为年(四舍五入)
df_processed['age_years'] = (df_processed['age'] / 365.25).round().astype(int)
# 2. 计算BMI: BMI = weight(kg) / (height(m)^2)
df_processed['bmi'] = df_processed['weight'] / ((df_processed['height'] / 100) ** 2)
df_processed['bmi'] = df_processed['bmi'].round(2)
# 3. 异常值处理
# 删除舒张压 >= 收缩压的记录
invalid_bp = df_processed['ap_lo'] >= df_processed['ap_hi']
if invalid_bp.any():
print(f"删除 {invalid_bp.sum()} 条舒张压 >= 收缩压的异常记录")
df_processed = df_processed[~invalid_bp].copy()
# 删除血压极端异常值
# 收缩压 ∈ [90, 250], 舒张压 ∈ [60, 150]
bp_outliers = ~((df_processed['ap_hi'] >= 90) & (df_processed['ap_hi'] <= 250) &
(df_processed['ap_lo'] >= 60) & (df_processed['ap_lo'] <= 150))
if bp_outliers.any():
print(f"删除 {bp_outliers.sum()} 条血压极端异常值记录")
df_processed = df_processed[~bp_outliers].copy()
# 4. 删除不需要的列
# 删除id和原始age字段使用转换后的age_years
df_processed = df_processed.drop(['id', 'age'], axis=1)
print(f"预处理后数据形状: {df_processed.shape}")
print("数据预处理完成!")
return df_processed
except Exception as e:
print(f"数据加载和预处理失败: {str(e)}")
raise
def prepare_features_and_target(df):
"""
准备特征矩阵X和目标向量y
参数:
df: 预处理后的数据框
返回:
X: 特征矩阵
y: 目标向量
feature_names: 特征名称列表
"""
print("准备特征和目标变量...")
# 目标变量
y = df['cardio'].values
# 特征矩阵 - 删除目标变量
X = df.drop('cardio', axis=1)
print(f"特征矩阵形状: {X.shape}")
print(f"目标变量分布: 0={sum(y==0)}, 1={sum(y==1)}")
return X, y, X.columns.tolist()
def build_pipeline():
"""
构建机器学习Pipeline
返回:
Pipeline: 包含预处理和分类器的完整Pipeline
"""
print("构建机器学习Pipeline...")
# 定义特征类型
# 连续特征:需要标准化
numerical_features = ['age_years', 'bmi', 'ap_hi', 'ap_lo']
# 分类特征:需要独热编码
categorical_features = ['gender', 'cholesterol', 'gluc']
# 二元特征:直接使用(不需要编码)
binary_features = ['smoke', 'alco', 'active']
# 所有特征顺序
all_features = numerical_features + categorical_features + binary_features
# 创建列转换器
preprocessor = ColumnTransformer(
transformers=[
('num', StandardScaler(), numerical_features),
('cat', OneHotEncoder(drop='first', sparse_output=False, handle_unknown='ignore'),
categorical_features),
# 二元特征直接通过(不进行变换)
('binary', 'passthrough', binary_features)
],
remainder='drop' # 丢弃其他列
)
# 创建完整Pipeline
pipeline = Pipeline([
('preprocessor', preprocessor),
('classifier', XGBClassifier(
n_estimators=100,
max_depth=5,
learning_rate=0.1,
subsample=0.8,
colsample_bytree=0.8,
random_state=42,
eval_metric='logloss',
use_label_encoder=False
))
])
print("Pipeline构建完成")
return pipeline, all_features
def train_model(X, y, pipeline):
"""
训练模型
参数:
X: 特征矩阵
y: 目标向量
pipeline: 机器学习Pipeline
返回:
训练好的Pipeline
"""
print("开始训练模型...")
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
print(f"训练集大小: {X_train.shape}")
print(f"测试集大小: {X_test.shape}")
# 训练模型
pipeline.fit(X_train, y_train)
# 评估模型
train_score = pipeline.score(X_train, y_train)
test_score = pipeline.score(X_test, y_test)
print(f"训练集准确率: {train_score:.4f}")
print(f"测试集准确率: {test_score:.4f}")
# 特征重要性(如果可用)
if hasattr(pipeline.named_steps['classifier'], 'feature_importances_'):
importances = pipeline.named_steps['classifier'].feature_importances_
print(f"特征重要性数量: {len(importances)}")
# 获取特征名称(需要从预处理器中提取)
preprocessor = pipeline.named_steps['preprocessor']
# 获取转换后的特征名称
feature_names = []
# 数值特征名称
feature_names.extend(preprocessor.transformers_[0][2])
# 分类特征名称(独热编码后)
if len(preprocessor.transformers_) > 1:
cat_encoder = preprocessor.transformers_[1][1]
if hasattr(cat_encoder, 'get_feature_names_out'):
cat_features = cat_encoder.get_feature_names_out(
preprocessor.transformers_[1][2]
)
feature_names.extend(cat_features)
# 二元特征名称
if len(preprocessor.transformers_) > 2:
feature_names.extend(preprocessor.transformers_[2][2])
# 打印最重要的特征
if len(feature_names) == len(importances):
print("\nTop 10 特征重要性:")
indices = np.argsort(importances)[::-1]
for i in range(min(10, len(importances))):
print(f" {feature_names[indices[i]]}: {importances[indices[i]]:.4f}")
return pipeline
def save_pipeline(pipeline, all_features):
"""
保存Pipeline到文件
参数:
pipeline: 训练好的Pipeline
all_features: 特征名称列表
"""
print("保存模型和特征信息...")
# 创建模型保存目录
model_dir = Path(__file__).parent / "models"
model_dir.mkdir(exist_ok=True)
# 模型文件路径
model_path = model_dir / "cardio_predictor_model.pkl"
# 保存Pipeline对象
model_data = {
'pipeline': pipeline,
'feature_names': all_features,
'model_version': '1.0.0',
'description': 'CardioAI心血管疾病预测模型'
}
joblib.dump(model_data, model_path)
print(f"模型已保存到: {model_path}")
# 保存特征信息到单独文件(可选)
features_path = model_dir / "feature_info.txt"
with open(features_path, 'w', encoding='utf-8') as f:
f.write("CardioAI模型特征信息\n")
f.write("=" * 50 + "\n\n")
f.write("特征列表(按输入顺序):\n")
for i, feature in enumerate(all_features, 1):
f.write(f"{i:2d}. {feature}\n")
f.write("\n\n特征说明:\n")
f.write("- age_years: 年龄(岁),由原始天数转换而来\n")
f.write("- bmi: 身体质量指数,计算公式:体重(kg) / (身高(m)^2)\n")
f.write("- ap_hi: 收缩压mmHg\n")
f.write("- ap_lo: 舒张压mmHg\n")
f.write("- gender: 性别1=女性2=男性)\n")
f.write("- cholesterol: 胆固醇水平1=正常2=高于正常3=极高)\n")
f.write("- gluc: 血糖水平1=正常2=高于正常3=极高)\n")
f.write("- smoke: 吸烟0=否1=是)\n")
f.write("- alco: 饮酒0=否1=是)\n")
f.write("- active: 体育活动0=否1=是)\n")
print(f"特征信息已保存到: {features_path}")
return model_path
def main():
"""主函数"""
print("=" * 60)
print("CardioAI - 心血管疾病预测模型训练")
print("=" * 60)
try:
# 1. 加载和预处理数据
df = load_and_preprocess_data()
# 2. 准备特征和目标
X, y, original_features = prepare_features_and_target(df)
# 3. 构建Pipeline
pipeline, all_features = build_pipeline()
# 4. 训练模型
trained_pipeline = train_model(X, y, pipeline)
# 5. 保存模型
model_path = save_pipeline(trained_pipeline, all_features)
print("\n" + "=" * 60)
print("模型训练完成!")
print(f"模型文件: {model_path}")
print("下一步使用Flask应用部署模型")
print("=" * 60)
except Exception as e:
print(f"\n训练过程出现错误: {str(e)}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()