-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtitanic.py
58 lines (52 loc) · 1.56 KB
/
titanic.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
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB
# Importing dataset
data = pd.read_csv("train.csv")
# Convert categorical variable to numeric
data["Sex_cleaned"]=np.where(data["Sex"]=="male",0,1)
data["Embarked_cleaned"]=np.where(data["Embarked"]=="S",0,
np.where(data["Embarked"]=="C",1,
np.where(data["Embarked"]=="Q",2,3)
)
)
# Cleaning dataset of NaN
data=data[[
"Survived",
"Pclass",
"Sex_cleaned",
"Age",
"SibSp",
"Parch",
"Fare",
"Embarked_cleaned"
]].dropna(axis=0, how='any')
# Split dataset in training and test datasets
X_train, X_test = train_test_split(data, test_size=0.5, random_state=int(time.time()))
# Instantiate the classifier
gnb = GaussianNB()
used_features =[
"Pclass",
"Sex_cleaned",
"Age",
"SibSp",
"Parch",
"Fare",
"Embarked_cleaned"
]
# Train classifier
gnb.fit(
X_train[used_features].values,
X_train["Survived"]
)
y_pred = gnb.predict(X_test[used_features])
# Print results
print("Number of mislabeled points out of a total {} points : {}, performance {:05.2f}%"
.format(
X_test.shape[0],
(X_test["Survived"] != y_pred).sum(),
100*(1-(X_test["Survived"] != y_pred).sum()/X_test.shape[0])
))