-
Notifications
You must be signed in to change notification settings - Fork 0
/
godswillbewatching.py
131 lines (100 loc) · 2.61 KB
/
godswillbewatching.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# coding: utf-8
import pandas as pd
import math
from sklearn.ensemble import RandomForestClassifier
# Step one, load the data.
train_ds = pd.read_csv("./train.csv")
test_ds = pd.read_csv("./test.csv")
# Get gender: male is 1 female is 0
def get_sex(sex):
if sex == "male":
return 1
else:
return 0
# Where they came from? (Southamptom, Cherbourg, Queenstown). Whe guess Southamptom for the unkown.
def get_embarked(embarked):
if embarked in ['C']:
return 1
elif embarked in ['Q']:
return 2
else:
return 0
# Fix missing age values with median
def fix_age(age):
if math.isnan(age):
return 28
else:
return age
# Fix 0 or NaN fares
def fix_price(fare):
if fare == 0 or math.isnan(fare):
return 14.45
else:
return fare
# Family inside:
def family_inside(family):
if family > 0:
return 1
else:
return 0
# How much they paid for the fare?
def get_status(fare):
if fare >= 31:
return 0
elif 8 < fare < 31:
return 1
else:
return 2
# Create a mapping of the title_ids
def get_title(name):
title = name.split(' ')[1]
if title == 'Mr.':
return 0
elif title == 'Mrs.':
return 1
elif title == 'Miss.':
return 2
elif title == 'Master.':
return 3
elif title == 'Don.':
return 4
else:
return 5
# Fit the dataset
def fit_ds(ds):
ds['sex'] = ds['Sex'].apply(get_sex)
ds['title'] = ds['Name'].apply(get_title)
ds['price'] = ds['Fare'].apply(fix_price)
ds['age'] = ds['Age'].apply(fix_age)
ds['status'] = ds['price'].apply(get_status)
ds['family'] = ds['SibSp'].apply(family_inside)
ds['from'] = ds['Embarked'].apply(get_embarked)
return ds
# We generate fitted datasets
train_fds = fit_ds(train_ds)
test_fds = fit_ds(test_ds)
X_train = train_fds\
.drop("Survived", axis=1)\
.drop("Name", axis=1)\
.drop("Ticket", axis=1)\
.drop("Cabin", axis=1)\
.drop("Sex", axis=1)\
.drop("Embarked", axis=1)\
.drop("Age", axis=1)\
.drop("Fare", axis=1)
Y_train = train_fds["Survived"]
random_forest = RandomForestClassifier(n_estimators=1000)
random_forest.fit(X_train, Y_train)
test_fds = test_fds.drop("Name", axis=1)\
.drop("Ticket", axis=1)\
.drop("Cabin", axis=1)\
.drop("Sex", axis=1)\
.drop("Embarked", axis=1)\
.drop("Age", axis=1)\
.drop("Fare", axis=1)
prediction = random_forest.predict(test_fds)
submission = pd.DataFrame({
"Dude": test_ds["Name"],
"Survived": prediction
})
submission.to_csv("survivedornot.csv", index=False)