人工智能训练师(三级)实操考试 — 2.2.3 日常运动量随机森林预测模型开发与测试

← 返回题目列表 考核时间:20 分钟 20:00
工作任务

某健身平台希望通过用户的基本信息和运动习惯数据,使用机器学习算法预测用户的年龄段,从而为不同年龄段的用户提供个性化的运动推荐方案。

我们提供一个 fitness analysis 数据集(fitness analysis.csv),包含以下关键字段:

Your gender: 性别   Your age: 年龄段
How important is exercise to you ?: 运动重要性评分
How healthy do you consider yourself?: 健康自评分

具体要求

(1)加载数据集,对数据进行预处理(清理空格、转换分类变量等),选择相关特征进行建模。

(2)将数据集划分为训练集和测试集(测试集占比20%),创建随机森林回归模型(100棵决策树),训练并保存模型,进行预测。

(3)使用测试工具对模型进行测试,记录训练集分数、测试集分数、均方误差和决定系数。

(4)运用XGBoost回归模型(100棵树)分析算法中错误案例产生的原因并进行纠正,对比模型性能。

注意事项
  • 在代码的 橙色下划线 处填写正确的 Python 代码
  • 请勿修改源代码的其他部分
  • 填写完成后点击 "检查答案" 查看评分
  • 点击 "显示答案" 可直接查看所有参考答案
  • 点击 "重置" 清空所有填写内容
请在下划线处填写代码
当前得分
0 / 23
In [1] — 导入库 & 数据加载与预处理 4分
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 # 加载数据集 1分 df = # 显示前五行数据 1分 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?']] # 将分类变量转为数值变量 1分 X = (X) # 将年龄段转为数值变量 1分 y = (lambda x: int(x.split(' ')[0]))
In [2] — 数据划分 & 随机森林模型训练 8分
# 将数据集划分为训练集和测试集(测试集占比20%) 2分 X_train, X_test, y_train, y_test = (, random_state=42) # 创建随机森林回归模型(创建的决策树的数量为100) 2分 rf_model = (, random_state=42) # 训练随机森林回归模型 1分 # 保存训练好的模型 1分 with open('2.2.3_model.pkl', 'wb') as model_file: pickle. # 进行结果预测 1分 y_pred = results_df = pd.DataFrame(y_pred, columns=['预测结果']) results_df.to_csv('2.2.3_results.txt', index=False)
In [3] — 模型评估与测试报告 4分
# 使用测试工具对模型进行测试,并记录测试结果 # 训练集分数 1分 train_score = # 测试集分数 1分 test_score = # 均方误差 1分 mse = # 决定系数 1分 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')
In [4] — XGBoost 模型纠正与对比 7分
# 运用工具分析算法中错误案例产生的原因并进行纠正 # 初始化XGBoost回归模型(构建100棵树) 2分 xgb_model = (, random_state=42) # 训练XGBoost回归模型 1分 # 使用XGBoost回归模型在测试集上进行结果预测 1分 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')
答案检查结果