编写泰坦尼克号项目代码,并假设已经有了原始的pandas DataFrame titanic_df,其中包含embarked(登船港口)等列。
时间: 2024-10-12 18:13:04 浏览: 29
编写一个基本的泰坦尼克号预测项目的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
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
# 加载数据
titanic_df = pd.read_csv('titanic_data.csv') # 假设数据文件名是'titanic_data.csv'
# 数据预处理
# 将embarked列转换为数值类别
le = LabelEncoder()
titanic_df['Embarked'] = le.fit_transform(titanic_df['Embarked'])
# 创建特征和目标变量
X = titanic_df[['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked']]
y = titanic_df['Survived']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 模型训练
model = LogisticRegression()
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
# 评估
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
#
阅读全文