跳转到主要内容
2.2.3 · 建议 20 分钟 · 满分 23

日常运动量随机森林预测模型开发与测试

背景

随着人们健康意识的增强,越来越多的人开始关注日常运动和健康管理。使用提供的训练数据,补全 2.2.3.ipynb 代码。选择合适的特征,开发一个预测模型,基于个体性别、个体对运动的看法和个人健康评价来预测个体年龄。利用测试工具对模型进行测试,并对测试结果进行分析,完成测试报告,并运用工具对错误原因进行纠正。

工作任务

  1. 正确加载数据集,并显示前五行的数据。
  2. 使用随机森林模型进行模型训练,要求设定自变量和因变量,并根据自变量特征进行模型训练,最终将训练好的模型以文件名 2.2.3_model.pkl 保存到考生文件夹,结果文件以 2.2.3_results.txt 保存到考生文件夹。
  3. 使用测试工具对模型进行测试,并记录测试结果,命名 2.2.3_report.txt,保存到考生文件夹。
  4. 对测试结果进行详细分析,并编写测试报告,包括模型性能评估、错误分析及改进建议,写到 2.2.3.docx 答题卷文件。
  5. 运用工具分析算法中错误案例产生的原因并进行纠正,重新得到模型训练结果,以文件名 2.2.3_results_xgb.txt 保存到考生文件夹。

素材预览

fitness analysis.csv
Timestamp,Your name,Your gender,Your age,How important is exercise to you ?,How do you describe your current level of fitness ?,How often do you exercise?,...
2019/07/03 11:48:07 PM GMT+5:30,Parkavi,Female,19 to 25,2,Good,Never,...
2019/07/03 11:51:22 PM GMT+5:30,Nithilaa,Female,19 to 25,4,Very good,Never,...

代码填空

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
import pickle
from sklearn.metrics import mean_squared_error, r2_score
import xgboost as xgb

# 加载数据集
df = 

# 显示前五行数据
print()

# 去除所有字符串字段的前后空格
df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)

# 检查和清理列名
df.columns = df.columns.str.strip()

# 选择相关特征进行建模
X = df[['Your gender', 'How important is exercise to you ?', 'How healthy do you consider yourself?']]
X = (X)  # 将分类变量转为数值变量

# 将年龄段转为数值变量
y = (lambda x: int(x.split(' ')[0]))  # 假设年龄段为整数

# 将数据集划分为训练集和测试集(测试集占比20%)
X_train, X_test, y_train, y_test = (, random_state=42)

# 创建随机森林回归模型(创建的决策树的数量为100)
rf_model = (, random_state=42)
# 训练随机森林回归模型


# 保存训练好的模型
with open('2.2.3_model.pkl', 'wb') as model_file:
    pickle.

# 进行结果预测
y_pred = 
results_df = pd.DataFrame(y_pred, columns=['预测结果'])
results_df.to_csv('2.2.3_results.txt', index=False)

# 使用测试工具对模型进行测试,并记录测试结果
train_score =    #训练集分数
test_score =     #测试集分数
mse =   #均方误差
r2 =   #决定系数
with open('2.2.3_report.txt', 'w') as report_file:
    report_file.write(f'训练集得分: {train_score}\n')
    report_file.write(f'测试集得分: {test_score}\n')
    report_file.write(f'均方误差(MSE): {mse}\n')
    report_file.write(f'决定系数(R^2): {r2}\n')

# 运用工具分析算法中错误案例产生的原因并进行纠正
# 初始化XGBoost回归模型(构建100棵树)
xgb_model = (, random_state=42)
# 训练XGBoost回归模型

# 使用XGBoost回归模型在测试集上进行结果预测
y_pred_xgb = 

results_df_xgb = pd.DataFrame(y_pred_xgb, columns=['预测结果'])
results_df_xgb.to_csv('2.2.3_results_xgb.txt', index=False)

with open('2.2.3_report_xgb.txt', 'w') as xgb_report_file:
    xgb_report_file.write(f'XGBoost训练集得分: {}\n')
    xgb_report_file.write(f'XGBoost测试集得分: {}\n')
    xgb_report_file.write(f'XGBoost均方误差(MSE): {}\n')
    xgb_report_file.write(f'XGBoost决定系数(R^2): {)}\n')