【机器学习笔记(七)】之泰坦尼克号获救问题 求解思路(完整代码-详细注释)

    技术2026-02-15  16

    本文章由公号【开发小鸽】发布!欢迎关注!!!

    老规矩–妹妹镇楼:

    泰坦尼克号获救问题(线性回归 / 逻辑回归 / 随机森林 求解思路)

    一. 预处理 数据表格

    首先分析表格中的数据,可以看到 Age 列中的数据是有缺失的,因此,需要补齐所有空缺的Age数据,用中位数。再看Sex列中的性别字符串转换成 数字,便于计算。将所有 male替换为 0, female 替换为1。同理, Embarked 列也要转换成数字,由于该列中依然有缺失,需要填充,那就填充出现次数最多的S,再进行准换。

            数据预处理结束后,表格中的数据被补齐了,可以进行计算操作了。

    二. 交叉验证

    1. 设置验证集的原因

            在机器学习建模过程中,将数据分为训练集和测试集。测试集合训练集是完全分开的两个数据集,完全不参与训练,只是用于模型最终确定后,来测试模型的效果。而训练集又要分出一部分数据用来验证模型的训练效果,即验证集。验证集在每次训练集训练结束后,对模型的效果进行初步地测试。之所以要设置验证集,是因为训练数据会有过拟合的情况出现,即训练数据能够很好地匹配训练数据,但对于训练数据之外的数据效果非常差。验证集不参与训练,可以客观地评价模型对于训练集之外的数据的匹配度。

    2. 交叉验证原理

            交叉验证经常用于数据的验证,原理是将数据分为 n 组,每组数据都要作为一次验证集进行一次验证,而其余的 n-1 组数据作为训练集。这样一共要循环 n 次,验证 n 次,得到 n 个模型,这 n 个模型得到的 n 个误差计算均值,得到交叉验证误差。

    三. 训练

            设置 输入特征,标签,交叉验证,将验证结果与真实数据进行比对,计算准确率。

            线性回归,逻辑回归,随机森林只是不同的分类器。

    四. 代码如下,代码中有非常详细地注释:

    import pandas as pd titanic = pd.read_csv("titanic_train.csv") #print(titanic.head()) #print(titanic.describe()) #预处理 数据表格 """首先分析表格中的数据,可以看到 Age 列中的数据是有缺失的, 因此,需要补齐所有空缺的数据,用中位数""" titanic["Age"] = titanic["Age"].fillna(titanic["Age"].median()) #print(titanic.describe()) # Sex列中的性别字符串转换成 数字,便于计算 # Sex 列中的单独值 #print( titanic["Sex"].unique()) #将所有 male替换为 0, female 替换为1 titanic.loc[titanic["Sex"]=="male", "Sex"] = 0 titanic.loc[titanic["Sex"]=="female", "Sex"] = 1 #print(titanic["Sex"].unique()) #同理, Embarked 列也要转换成数字 #print(titanic["Embarked"].unique()) #由于该列中依然有缺失,需要填充,那就填充出现次数最多的S titanic["Embarked"] = titanic["Embarked"].fillna('S') titanic.loc[titanic["Embarked"]=="S", "Embarked"] = 0 titanic.loc[titanic["Embarked"]=="C", "Embarked"] = 1 titanic.loc[titanic["Embarked"]=="Q", "Embarked"] = 2 #print(titanic["Embarked"].unique()) #数据预处理结束 """线性回归""" #需要用到 sklearn这个库里的 线性回归 from sklearn.linear_model import LinearRegression # 数据的交叉验证,即数据分为训练集与测试集,而训练集又细分为训练集与验证集, # 训练集与验证集通过多次的交叉,如训练集被分为4份,1, 2, 3, 4,第一次交叉验证是用 # 1,2,3训练,4来验证;第二次交叉验证是用1,2,4来训练,3来验证 from sklearn.model_selection import KFold #数据的输入特征 predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"] #初始化一个线性回归训练器 alg = LinearRegression() """ 通过交叉验证 KFold 生成 训练集与验证集 参数n_splits:将训练集分为 n 份,n份数据,每一份都要作为作为一次验证集来验证训练的结果,一共 n 次循环,其余n-1份数据作为训练集进行训练。 参数 shuffle:表示是否打乱数据的顺序 ,bool 类型 参数 random_state: 同一个数字保证每次循环都是分成同样的份 """ kf = KFold(n_splits=3, shuffle=False, random_state=None) #验证集的结果 predictions= [] for train_index, test_index in kf.split(titanic): #检查 训练集 与 验证集的大小 #print(type(train_index)) #print(train_index.size) #print(test_index.size) #训练输入特征集 train_predictors = (titanic[predictors].iloc[train_index,:]) #训练的标签集 train_target = titanic["Survived"].iloc[train_index] #用线性回归训练器训练数据, 输入特征,标签 alg.fit(train_predictors, train_target) #训练完数据后,用验证集对训练结果进行验证, 每次 1/3的数据量验证,3次,全部验证完 test_prediction = alg.predict(titanic[predictors].iloc[test_index,:]) #将验证结果加入验证结果列表中 predictions.append(test_prediction) #print(type(predictions)) list #print(len(predictions[0])) 297 #print(type(predictions[0])) ndarray #print(predictions[0].shape) 297,1 """获得所有数据的验证结果后,就要来计算一下这个模型的准确率, 即正确预测存活率这个标签的概率。 """ import numpy as np #将所有的验证结果整合成一列 predictions = np.concatenate(predictions, axis=0) #print(predictions.shape) 891,1 #验证结果以 0.5为基准,大于0.5为存活,不大于0.5为死亡 predictions[predictions > .5] = 1 predictions[predictions <= .5] = 0 #计算正确率, 将验证结果集与真实数据比较,得出比对正确的索引 accuracy = sum(predictions == titanic["Survived"]) / len(predictions) print(accuracy) """ 逻辑回归计算 """ from sklearn.model_selection import cross_val_score from sklearn.linear_model import LogisticRegression #初始化分类器 alg2 = LogisticRegression(random_state=1) #同样交叉验证,用另一种方法, cross_validation scores = cross_val_score(alg2, titanic[predictors], titanic["Survived"], cv=3) #求取结果的均值,因为交叉验证的每一份都计算了准确率 print(scores.mean()) """ 用集成算法来提高结果的准确性,随机森林 """ #随机森林分类器 from sklearn.ensemble import RandomForestClassifier """ 随机森林分类器的参数: n_estimators: 随机森林中树的个数 min_samples_split: 剪枝时限制的最小深度 min_samples_leaf: 剪枝限制的叶子节点的最小样本数 """ #初始化随机森林分类器 alg3 = RandomForestClassifier(n_estimators=100, min_samples_split=4,min_samples_leaf=4, random_state=1) #交叉验证 kf3 = KFold(n_splits=3,shuffle=False, random_state=1) #计算每次交叉验证的均值 scores3 = cross_val_score(alg3, titanic[predictors], titanic["Survived"], cv=kf3) print(scores3.mean())
    Processed: 0.010, SQL: 9