泰坦尼克号幸存者预测实验代码
时间: 2024-12-13 18:24:21 浏览: 7
泰坦尼克号幸存者预测实验通常是一个机器学习项目,目的是基于乘客的信息(如年龄、性别、舱位等级等)预测他们在泰坦尼克号沉船事故中是否存活下来。这个过程涉及数据预处理、特征工程、模型训练和评估。以下是使用Python和一些流行库(如pandas、numpy、scikit-learn等)进行简单预测的一个示例:
```python
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
# 加载数据
url = "https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv"
data = pd.read_csv(url)
# 数据预处理
data['Sex'] = LabelEncoder().fit_transform(data['Sex'])
data['Embarked'] = data['Embarked'].fillna('S') # 填充缺失值
data.drop(['Name', 'Ticket', 'Cabin'], axis=1, inplace=True) # 可能不需要所有列
# 特征选择和编码
features = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare']
X = data[features]
y = data['Survived']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 特征缩放
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 模型训练
model = LogisticRegression()
model.fit(X_train, y_train)
# 预测并评估
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
阅读全文