决策树实现泰坦尼克生还预测代码
时间: 2023-09-16 08:14:25 浏览: 108
好的,我来为您提供决策树实现泰坦尼克生还预测的代码,代码如下:
```python
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 读取数据
data = pd.read_csv('titanic.csv')
# 数据预处理,去掉无关特征和缺失值
data.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1, inplace=True)
data = data.dropna()
# 将分类变量转换为数值变量
data['Sex'] = data['Sex'].map({'female': 0, 'male': 1}).astype(int)
embarked = pd.get_dummies(data['Embarked'], prefix='Embarked')
data = pd.concat([data, embarked], axis=1)
data.drop(['Embarked'], axis=1, inplace=True)
# 定义自变量和因变量
X = data.drop(['Survived'], axis=1)
y = data['Survived']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 建立决策树模型
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
# 预测测试集结果
y_pred = model.predict(X_test)
# 输出模型准确率
print('Accuracy:', accuracy_score(y_test, y_pred))
```
以上就是决策树实现泰坦尼克生还预测的代码,希望对您有所帮助。
阅读全文