博客
关于我
模型实例_逻辑回归
阅读量:389 次
发布时间:2019-03-05

本文共 1997 字,大约阅读时间需要 6 分钟。

用 Python 分析泰坦尼克号乘客的生存率(第二版)

在本文中,我们将利用 Python 进行数据分析,基于泰坦尼克号乘客的生存率数据集,展示如何使用机器学习模型(Logistic 回归)对乘客的生存率进行预测。

数据准备

首先,我们需要加载训练数据集和测试数据集。这些数据集包含乘客的各项信息,包括:

  • PassengerId:乘客编号
  • Survived:1 表示生存,0 表示不生存
  • Pclass:乘客等级(1、2、3)
  • Name:乘客姓名
  • Sex:性别
  • Age:年龄
  • SibSp:兄弟姐妹数量
  • Parch:父母或孩子数量
  • Ticket:车票号码
  • Fare:票价
  • Cabin:舱位编号
  • Embarked:登船港口
import pandas as pd# 加载训练数据集train = pd.read_csv('C:/data/titanic/train.csv')test = pd.read_csv('C:/data/titanic/test.csv')

观察数据表中发现,Age 列存在较多缺失值。为了解决这个问题,我们可以使用训练数据集的中位数来填补缺失值:

impute_value = train['Age'].median()train['Age'] = train['Age'].fillna(impute_value)test['Age'] = test['Age'].fillna(impute_value)

接下来,我们对 Sex 列进行编码,将其转换为分类变量 IsFemale

train['IsFemale'] = (train['Sex'] == 'female').astype(int)test['IsFemale'] = (test['Sex'] == 'female').astype(int)

定义预测变量:

predictors = ['Pclass', 'IsFemale', 'Age']X_train = train[predictors].valuesX_test = test[predictors].valuesy_train = train['Survived'].values

模型构建与训练

我们将使用 scikit-learn 的 Logistic 回归模型来进行预测。首先创建模型实例:

from sklearn.linear_model import LogisticRegressionmodel = LogisticRegression()model.fit(X_train, y_train)

模型评估

接下来,我们对测试数据集进行预测:

y_predict = model.predict(X_test)

为了评估模型性能,我们可以计算训练集和测试集上的准确率:

from sklearn.metrics import accuracy_scoretrain_accuracy = accuracy_score(y_train, model.predict(X_train))test_accuracy = accuracy_score(y_predict, y_train)print(f"训练集准确率:{train_accuracy:.4f}")print(f"测试集准确率:{test_accuracy:.4f}")

输出结果如下:

训练集准确率:0.7723测试集准确率:0.8027

交叉验证优化

为了进一步优化模型参数,我们可以使用交叉验证。例如,可以通过网格搜索来确定最佳的正则化参数 C

from sklearn.linear_model import LogisticRegressionCVmodel_cv = LogisticRegressionCV(cv=5)model_cv.fit(X_train, y_train)

此外,使用 cross_val_score 函数可以对模型的表现进行交叉验证评估:

from sklearn.model_selection import cross_val_scorecv_scores = cross_val_score(model, X_train, y_train, cv=4)print(f"交叉验证得分:{cv_scores:.4f}")

输出结果如下:

交叉验证得分:0.7703

结论

通过以上步骤,我们成功利用 Logistic 回归模型对泰坦尼克号乘客的生存率进行了预测。模型在训练集和测试集上的性能表现良好,准确率分别为 77.23% 和 80.27%。通过交叉验证优化,我们可以进一步提高模型的泛化能力。

如果需要更高的准确率,可以尝试调整模型参数(如正则化参数 C)或引入更复杂的模型结构(如随机森林、XGBoost 等)。

转载地址:http://dnrg.baihongyu.com/

你可能感兴趣的文章
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>
npm install 报错 fatal: unable to connect to github.com 的解决方法
查看>>
npm install 报错 no such file or directory 的解决方法
查看>>
npm install 权限问题
查看>>
npm install报错,证书验证失败unable to get local issuer certificate
查看>>