-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathTitanic_Machine_Learning.py
114 lines (53 loc) · 1.63 KB
/
Titanic_Machine_Learning.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
#!/usr/bin/env python
# coding: utf-8
# In[22]:
import numpy as np
import pandas as pd
#The Machine learning alogorithm
from sklearn.ensemble import RandomForestClassifier
# Test train split
from sklearn.model_selection import train_test_split
# Just to switch off pandas warning
pd.options.mode.chained_assignment = None
# Used to write our model to a file
import joblib
# In[23]:
data = pd.read_csv("titanic_train.csv")
data.head()
# In[24]:
data.columns
# In[25]:
median_age = data['age'].median()
print("Median age is {}".format(median_age))
# In[26]:
data['age'].fillna(median_age, inplace = True)
data['age'].head()
# In[27]:
data_inputs = data[["pclass", "age", "sex"]]
data_inputs.head()
# In[28]:
expected_output = data[["survived"]]
expected_output.head()
# In[29]:
data_inputs["pclass"].replace("3rd", 3, inplace = True)
data_inputs["pclass"].replace("2nd", 2, inplace = True)
data_inputs["pclass"].replace("1st", 1, inplace = True)
data_inputs.head()
# In[30]:
data_inputs["sex"] = np.where(data_inputs["sex"] == "female", 0, 1)
data_inputs.head()
# In[31]:
inputs_train, inputs_test, expected_output_train, expected_output_test = train_test_split (data_inputs, expected_output, test_size = 0.33, random_state = 42)
print(inputs_train.head())
print(expected_output_train.head())
# In[32]:
rf = RandomForestClassifier (n_estimators=100)
# In[33]:
rf.fit(inputs_train, expected_output_train)
# In[34]:
accuracy = rf.score(inputs_test, expected_output_test)
print("Accuracy = {}%".format(accuracy * 100))
assert(accuracy > .77)
# In[35]:
joblib.dump(rf, "titanic_model1", compress=9)
# In[ ]: