Skip to content

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

1.导入库

python
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
  • pandas :数据处理库
  • train_test_split :数据集划分⼯具
  • RandomForestRegressor :随机森林回归模型
  • pickle : Python 对象序列化模块
  • mean_squared_errorr2_score :回归评估指标
  • xgboost : XGBoost 梯度提升库

2.数据加载与预览

python
df = pd.read_csv('fitness analysis.csv')
print(df.head())
  • pd.read_csv() :读取 CSV ⽂件

    • 参数:⽂件路径 ('fitness analysis.csv')
  • head() :显⽰前 5 行数据

  • 功能:加载数据并初步检查数据结构

3.数据清洗

python
df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
df.columns = df.columns.str.strip()
  • applymap() :对整个 DataFrame 应⽤函数

    • lambda 函数:去除字符串字段前后空格
  • str.strip() :去除列名中的空格

  • 功能:统⼀数据格式,避免因空格导致的处理问题

4. 特征⼯程

python
X = df[['Your gender', 'How important is exercise to you ?', 'How healthy do you consider yourself?']]
X = pd.get_dummies(X)  # 将分类变量转为数值变量
y = df['Your age'].apply(lambda x: int(x.split(' ')[0]))
  • pd.get_dummies() :将分类变量转为哑变量 (one-hot 编码 )

  • apply() :处理年龄数据

    • split(' ')[0] :假设年龄格式为 "25 years" ,提取数字部分
    • int() :转换为整数
  • 功能:构建数值型特征矩阵和⽬标向量

5.数据集划分

python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  • train_test_split() :划分训练 / 测试集
    • test_size=0.2 :测试集占 20%
    • random_state=42 :固定随机种⼦保证可重复性

6.随机森林模型

python
rf_model = RandomForestRegressor(n_estimators=100, random_state=42)
rf_model.fit(X_train, y_train)
  • RandomForestRegressor() :创建随机森林模型

    • n_estimators=100 : 100 棵决策树
    • random_state=42 :固定随机种⼦
  • fit() :训练模型

7.模型保存

python
with open('2.2.3_model.pkl', 'wb') as model_file:
  pickle.dump(rf_model, model_file)
  • pickle.dump() :序列化保存模型
    • 'wb' :⼆进制写入模式
    • 保存到 '2.2.3_model.pkl'

8.预测与评估

python
y_pred = rf_model.predict(X_test)
results_df = pd.DataFrame(y_pred, columns=['预测结果'])
results_df.to_csv('2.2.3_results.txt', index=False)

train_score = rf_model.score(X_train, y_train)
test_score = rf_model.score(X_test, y_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
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')
  • predict() :⽣成预测结果
  • score() :计算 R² 决定系数
  • mean_squared_error() :计算均⽅误差
  • r2_score() :计算 R² 分数
  • 保存预测结果和多种评估指标

9.XGBoost 模型对⽐

python
xgb_model = xgb.XGBRegressor(n_estimators=100, random_state=42)
xgb_model.fit(X_train, y_train)
y_pred_xgb = xgb_model.predict(X_test)

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训练集得分: {xgb_model.score(X_train, y_train)}\n')
  xgb_report_file.write(f'XGBoost测试集得分: {xgb_model.score(X_test, y_test)}\n')
  xgb_report_file.write(f'XGBoost均方误差(MSE): {mean_squared_error(y_test, y_pred_xgb)}\n')
  xgb_report_file.write(f'XGBoost决定系数(R^2): {r2_score(y_test, y_pred_xgb)}\n')
  • XGBRegressor() :创建 XGBoost 模型

    • 参数与随机森林类似
  • 相同流程进⾏训练和评估

  • 功能:与随机森林模型进⾏性能对⽐

10.错误分析

欠拟合:训练集得分较低且测试集得分为负,表明模型既没有很好地拟合训练数据,也没有泛化到新数据上,即出现了严重的欠拟合现象。

11.改进建议

  • 增加模型的复杂度

  • 特征工程:重新审视并优化特征选择,确保所选特征对于预测年龄具有较强的关联性。

  • 超参数调优:使用网格搜索(Grid Search)或随机搜索(Randomized Search)来寻找最佳的超参数组合,以提高模型性能。

  • 检查数据分布: 确认数据集是否代表了真实的分布,特别是目标变量(年龄)是否有足够的代表