02-随机森林-泰坦尼克号顾客生存预测

📅 2026/7/21 5:39:57
02-随机森林-泰坦尼克号顾客生存预测
1. 需求分析根据乘客特征预测是否幸存二分类。本案例用随机森林建模。2. 数据说明数据来源https://www.kaggle.com/c/titanic/data字段含义PassengerId乘客 IDSurvived目标标签0 死亡 / 1 存活Pclass舱位1 一等 / 2 二等 / 3 三等Name姓名Sex性别 male/femaleAge年龄大量缺失SibSp船上兄弟姐妹 / 配偶数Parch船上父母 / 子女数Ticket船票编号Fare票价Cabin船舱号缺失极多Embarked登船港 C/Q/S3. 建模import pandas as pd from sklearn.model_selection import train_test_split3.1 加载数据data pd.read_csv(./data/train.csv) data.info()3.2 数据预处理提取特征和标签缺失值、异常值处理分类字段编码处理划分数据集# 1. 提取特征和标签 x data[[Pclass, Age, Sex]]].copy() y data[Survived].copy() # 2. 缺失值处理 x[Age] x[Age].fillna(x[Age].mean()) # 3. 分类特征one-hot编码 x pd.get_dummies(x, columns[Sex]) # 4. 划分数据集 x_train, x_test, y_train, y_test train_test_split(x, y, test_size0.2, random_state1234)3.3 特征工程归一化 / 标准化树模型一般不需要标准化3.4 模型训练、预测、评估3.4.1 场景1单个决策树estimator1 DecisionTreeClassifier() estimator1.fit(x_train, y_train) y_pre1 estimator1.predict(x_test) print(单个决策树模型效果\n, classification_report(y_test, y_pre1))3.4.2 场景2随机森林默认参数estimator2 RandomForestClassifier() estimator2.fit(x_train, y_train) y_pre2 estimator2.predict(x_test) print(随机森林默认参数模型效果\n, classification_report(y_test, y_pre2))3.4.3 场景3随机森林网格搜索交叉验证estimator3 RandomForestClassifier() param_grid { n_estimators: [30, 60, 90, 120], max_depth: [2,3,5,7] } # 3折交叉验证 gs_estimator GridSearchCV(estimator3, param_gridparam_grid, cv3) gs_estimator.fit(x_train, y_train) y_pre3 gs_estimator(x_test) print(随机森林网格搜索交叉验证模型效果\n, classification_report(y_test, y_pre3)) print(最佳参数, gs_estimator.best_params_)继续调参或选一个表现好的模型作为最终模型