Kaggle -- Titanic - Machine Learning from Disaster

新手kaggle之旅:1 . 泰坦尼克号

使用一个简单的决策树进行模型构建,达到75.8%的准确率(有点低,但是刚开始)

完整代码如下:

复制代码
import pandas as pd
import numpy as np

df = pd.read_csv("train.csv")

df.info

label = ['Pclass','Sex','Age','SibSp','Fare','Embarked']

x = df[label]
y = df['Survived']
print(x.loc[0])

x['Embarked'] = x['Embarked'].map({'C': 1, 'Q': 2, 'S': 3})


x['Sex'] = x['Sex'].map({'male': 1,'female' : 2})
print(x.loc[0])

x = x.fillna(x.mean())


import sklearn
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

train_x,test_x,train_y,test_y = train_test_split(x,y,test_size=0.2,random_state=42,shuffle=True)

clf = DecisionTreeClassifier()
clf.fit(train_x,train_y)


y_pred = clf.predict(test_x)

accuracy = accuracy_score(y_pred,test_y)
print(f"Accuracy: {accuracy * 100:.2f}%")


res = pd.read_csv('test.csv')
print(res.loc[0])


res_x = res[label]
res_x['Embarked'] = res_x['Embarked'].map({'C': 1, 'Q': 2, 'S': 3})
res_x['Sex'] = res_x['Sex'].map({'male': 1,'female' : 2})
print(res_x.loc[0])

res_x = res_x.fillna(res_x.mean())


pred = clf.predict(res_x)
print(pred[0])

ans = res[['PassengerId']].copy()
ans['Survived'] = pred

print(ans.loc[0])

ans.to_csv("ans.csv")
相关推荐
蓝婷儿10 分钟前
6个月Python学习计划 Day 17 - 继承、多态与魔术方法
开发语言·python·学习
Mikhail_G34 分钟前
Python应用变量与数据类型
大数据·运维·开发语言·python·数据分析
molunnnn1 小时前
day 18进行聚类,进而推断出每个簇的实际含义
机器学习·数据挖掘·聚类
Matrix_111 小时前
论文阅读:Matting by Generation
论文阅读·人工智能·计算摄影
Humbunklung1 小时前
机器学习算法分类
算法·机器学习·分类
hello kitty w1 小时前
Python学习(7) ----- Python起源
linux·python·学习
一叶知秋秋1 小时前
python学习day39
人工智能·深度学习·学习
Ai多利1 小时前
深度学习登上Nature子刊!特征选择创新思路
人工智能·算法·计算机视觉·多模态·特征选择
几道之旅1 小时前
MCP(Model Context Protocol)与提示词撰写
人工智能
站大爷IP1 小时前
Python文本序列的类型
python