泰坦尼克号 决策树分类python代码
时间: 2024-11-06 10:10:12 浏览: 23
python泰坦尼克号.zip
5星 · 资源好评率100%
泰坦尼克号的数据集是一个经典的机器学习入门案例,通常用于训练决策树模型。在这个例子中,我们将使用Python的scikit-learn库来构建一个决策树,预测乘客是否在泰坦尼克号沉船事故中存活。首先,确保已安装了必要的库,如pandas、numpy和sklearn。
```python
# 导入所需的库
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# 加载数据集
url = "https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv"
titanic_data = pd.read_csv(url)
# 数据预处理(清洗、缺失值处理等)
titanic_data = titanic_data.dropna(subset=['Survived', 'Age', 'Sex', 'Pclass']) # 示例,假设这些特征对生存有影响
titanic_data['Sex'] = titanic_data['Sex'].map({'male': 0, 'female': 1}) # 将性别转换为数值
# 特征选择和编码
features = ['Pclass', 'Sex', 'Age']
X = titanic_data[features]
y = titanic_data['Survived']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建并训练决策树模型
clf = DecisionTreeClassifier(random_state=42)
clf.fit(X_train, y_train)
# 预测测试集结果
y_pred = clf.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
#
阅读全文