【机器学习实战】基于python对泰坦尼克幸存者进行数据分析与预测
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction import DictVectorizer
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score
# 读取数据
titanic_data = pd.read_csv('titanic_data.csv')
# 分离特征和目标
X = titanic_data[titanic_data.select_dtypes(exclude=['object']).columns]
y = titanic_data['survived']
# 特征工程:对类别变量进行one-hot编码
categorical_features = ['sex', 'n_siblings_spouses', 'parch', 'class', 'deck', 'embark_town', 'alone']
preprocessor = ColumnTransformer(
transformers=[
('one_hot_encoder', OneHotEncoder(handle_unknown='ignore'), categorical_features)
])
# 初始化随机森林分类器
rf_classifier = make_pipeline(preprocessor, RandomForestClassifier())
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练模型
rf_classifier.fit(X_train, y_train)
# 进行预测
y_pred = rf_classifier.predict(X_test)
# 评估模型性能
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy*100:.2f}%")
这段代码使用了sklearn
库中的随机森林分类器来解决分类问题。首先,我们读取了泰坦尼克的数据集,并将其分为特征X
和目标y
。然后,我们使用ColumnTransformer
对类别特征进行one-hot编码,并初始化随机森林分类器。接着,我们使用train_test_split
划分数据集为训练集和测试集,并训练模型。最后,我们使用测试集来评估模型性能,并打印出准确率。
评论已关闭