-
Notifications
You must be signed in to change notification settings - Fork 0
/
notebookpy.py
359 lines (312 loc) · 9.88 KB
/
notebookpy.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#%% md
# In this notebook we show the process to train and deploy a model primarily utilizing Python and Docker.
#
# The data of interest is the titanic data where we predict whether a passenger survive or not.
#
# Data source: [kaggle](https://www.kaggle.com/competitions/titanic/data).
#%%
import pickle
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.feature_extraction import DictVectorizer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import accuracy_score, confusion_matrix, ConfusionMatrixDisplay, precision_score, recall_score, f1_score, confusion_matrix, classification_report
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
import os
#%%
dir = os.getcwd()
#%%
train = pd.read_csv(dir+"/data/train.csv")
train.info()
#%% md
# # Data Cleaning and Preprocessing
#
# We remove PassengerId, Name, Cabin, and Ticket from the data.
#%%
train_new = train.drop(['PassengerId', 'Name', 'Cabin', 'Ticket'], axis=1)
#%%
train_new.info()
#%% md
# Now, we fill the missing value in the age with the mean, and that of Embarked with the mode.
#%%
mode_embarked = train_new.Embarked.mode()
print('Mode of Embarked:' ,mode_embarked)
#%%
mean_age = round(train_new.Age.mean(), 2)
print('Mean age:', mean_age)
print('Mode of Embarked:' ,mode_embarked[0])
#%%
mode_embarked[0]
#%%
# train_new.fillna({train_new['Age']:mean_age}, inplace=True)
# train_new.fillna({train_new['Embarked']:mode_embarked[0]}, inplace=True)
#%%
train_new.Age.fillna(mean_age, inplace=True)
train_new.Embarked.fillna(mode_embarked[0], inplace=True)
#%%
train_new.info()
#%% md
# # EDA
#%%
train_new.Embarked.value_counts()
#%%
train_new.Survived.value_counts().plot(kind='bar', color='skyblue', edgecolor='black')
plt.title('Survived Value Counts')
plt.xlabel('Survived')
plt.ylabel('Counts')
plt.xticks(rotation=0) # Keep labels horizontal
plt.grid(axis='y', linestyle='--', alpha=0.7)
# Show the plot
plt.show()
#%%
train_new.Sex.value_counts().plot(kind='bar', color='skyblue', edgecolor='black')
plt.title('Gender Value Counts')
plt.xlabel('Gender')
plt.ylabel('Counts')
plt.xticks(rotation=0) # Keep labels horizontal
plt.grid(axis='y', linestyle='--', alpha=0.7)
# Show the plot
plt.show()
#%%
# a histogram
train_new['Age'].plot.hist(bins=10, color='lightblue', edgecolor='black')
plt.title('Age Distribution')
plt.xlabel('Age')
plt.ylabel('Frequency')
plt.grid(axis='y', linestyle='--', alpha=0.7)
# Show the plot
plt.show()
#%%
train_new.SibSp.value_counts().plot(kind='bar', color='skyblue', edgecolor='black')
plt.title('# of siblings/spouses aboard the Titanic Counts')
plt.xlabel('# of siblings/spouses')
plt.ylabel('Counts')
plt.xticks(rotation=0) # Keep labels horizontal
plt.grid(axis='y', linestyle='--', alpha=0.7)
# Show the plot
plt.show()
#%%
train_new.Parch.value_counts().plot(kind='bar', color='skyblue', edgecolor='black')
plt.title('# of parents/children aboard the Titanic Counts')
plt.xlabel('# of parents/children')
plt.ylabel('Counts')
plt.xticks(rotation=0) # Keep labels horizontal
plt.grid(axis='y', linestyle='--', alpha=0.7)
# Show the plot
plt.show()
#%%
# a histogram
train_new['Fare'].plot.hist(bins=50, color='lightblue', edgecolor='black')
plt.title('Passenger fare Distribution')
plt.xlabel('Fare')
plt.ylabel('Frequency')
plt.grid(axis='y', linestyle='--', alpha=0.7)
# Show the plot
plt.show()
#%%
train_new.Embarked.value_counts().plot(kind='bar', color='skyblue', edgecolor='black')
plt.title('Embarked Value Counts')
plt.xlabel('Embarked')
plt.ylabel('Counts')
plt.xticks(rotation=0) # Keep labels horizontal
plt.grid(axis='y', linestyle='--', alpha=0.7)
# Show the plot
plt.show()
#%% md
# Now, we do some bivariate plots.
#%%
# Scatter plot
plt.scatter(train_new['Age'], train_new['Survived'], color='blue', alpha=0.6)
# Customize the plot
plt.title('Age vs Survival')
plt.xlabel('Age')
plt.ylabel('Survived')
plt.yticks([0, 1], ['No', 'Yes'])
plt.grid(axis='y', linestyle='--', alpha=0.7)
# Show the plot
plt.show()
#%%
# Boxplot
sns.boxplot(x='Survived', y='Age', data=train_new)
# Customize the plot
plt.title('Age Distribution by Survival')
plt.xlabel('Survived')
plt.ylabel('Age')
plt.xticks([0, 1], ['No', 'Yes'])
# Show the plot
plt.show()
#%%
plt.figure(figsize=(8, 5))
ax = sns.countplot(x='Survived', hue='Sex', data=train_new, palette='Set2')
# Annotate the bars with their values
for container in ax.containers:
ax.bar_label(container, fmt='%d', label_type='edge', padding=3)
# Customize the plot
plt.title('Survival by Gender')
plt.xlabel('Survived')
plt.ylabel('Count')
plt.xticks([0, 1], ['No', 'Yes'])
# Show the plot
plt.show()
#%%
# Create a count plot for Survived and Embarked
plt.figure(figsize=(8, 5))
ax = sns.countplot(x='Survived', hue='Embarked', data=train_new, palette='Set2')
# Annotate the bars with their values
for container in ax.containers:
ax.bar_label(container, fmt='%d', label_type='edge', padding=3)
# Customize the plot
plt.title('Survival by Embarked')
plt.xlabel('Survived')
plt.ylabel('Count')
plt.xticks([0, 1], ['No', 'Yes'])
# Show the plot
plt.show()
#%%
# Create a boxplot for Fare and Survived
plt.figure(figsize=(8, 5))
sns.boxplot(x='Survived', y='Fare', data=train_new, palette='Set2')
# Customize the plot
plt.title('Fare Distribution by Survival')
plt.xlabel('Survived')
plt.ylabel('Fare')
plt.xticks([0, 1], ['No', 'Yes'])
# Show the plot
plt.show()
#%% md
# # Models
#
# At the end of our EDA, we build some models. We use the Logistic Regression, and Naive Bayes Model to solve the classification problem.
#%%
train_new
#%%
train_new.info()
#%%
y = train_new.Survived
X = train_new.drop(['Survived'], axis=1)
#%%
categorical_columns = list(X.dtypes[X.dtypes == 'object'].index)
numerical_columns = list(X.dtypes[X.dtypes != 'object'].index)
categorical_columns, numerical_columns
#%%
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
#%%
from sklearn.feature_extraction import DictVectorizer
def transform_to_vector(X, dv=None):
"""
Transforms a DataFrame into a vectorized format using DictVectorizer.
Parameters:
X (pd.DataFrame): The input DataFrame to be transformed.
dv (DictVectorizer, optional): A pre-fitted DictVectorizer instance.
If None, a new instance will be created and fitted.
Returns:
sparse_matrix: The vectorized sparse matrix.
DictVectorizer: The DictVectorizer instance (either newly fitted or provided).
"""
# Convert DataFrame to a list of dictionaries
dicts = X.to_dict(orient='records')
# If no DictVectorizer is provided, fit a new one
if dv is None:
dv = DictVectorizer()
vectorized_data = dv.fit_transform(dicts)
else:
# Use the provided DictVectorizer for transformation
vectorized_data = dv.transform(dicts)
return vectorized_data, dv
#%%
# dicts = X_train.to_dict(orient = 'records')
# dv = DictVectorizer()
# X_train2 = dv.fit_transform(dicts)
# X_train2
X_train2, dv = transform_to_vector(X_train)
#%% md
# ## Logistic Reg
#%%
lr = LogisticRegression(random_state=42, max_iter=10000)
params_lr = {
'penalty': ['elasticnet'],
'solver' : ['saga'],
'l1_ratio' : np.arange(0., 1.0, 0.1),
}
# Instantiate the grid search model
grid_search_lr = GridSearchCV(estimator=lr,
param_grid=params_lr,
cv = 5,
n_jobs=-1, verbose=1, scoring="accuracy")
#%%
%%time
grid_search_lr.fit(X_train2, y_train)
#%%
grid_search_lr.best_score_, grid_search_lr.best_estimator_
#%%
lr_best = grid_search_lr.best_estimator_
print(lr_best)
lr_best.fit(X_train2, y_train)
#%%
X_test2, _ = transform_to_vector(X_test, dv=dv)
# Predict on the test set
y_pred = lr_best.predict(X_test2)
# train_features, test_features, train_labels, test_labels
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average='weighted')
recall = recall_score(y_test, y_pred, average='weighted')
f1 = f1_score(y_test, y_pred, average='weighted')
print(f'Accuracy: {accuracy:.4f}')
print(f'Precision: {precision:.4f}')
print(f'Recall: {recall:.4f}')
print(f'F1 Score: {f1:.4f}')
# Display a detailed classification report
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
#%% md
# ## Naive Bayes
#%%
# Define the parameter grid
param_grid = {'var_smoothing': [1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3]}
#%%
%%time
# Initialize the model
nb_model = GaussianNB()
# Perform Grid Search
grid_search = GridSearchCV(nb_model, param_grid, cv=5, scoring='accuracy')
grid_search.fit(X_train2.toarray(), y_train)
# Get the best parameters and best score
best_alpha = grid_search.best_params_['var_smoothing']
best_score = grid_search.best_score_
print(f"Best alpha: {best_alpha}")
print(f"Best cross-validation accuracy: {best_score:.4f}")
#%%
print(grid_search.best_estimator_)
#%%
# Convert features to a dictionary format and vectorize
dicts_train = X_train.to_dict(orient='records')
dicts_test = X_test.to_dict(orient='records')
dv = DictVectorizer()
X_train_vectorized = dv.fit_transform(dicts_train)
X_test_vectorized = dv.transform(dicts_test)
# Initialize and train the Naive Bayes classifier
model = grid_search.best_estimator_
model.fit(X_train_vectorized.toarray(), y_train)
# Make predictions
y_pred = model.predict(X_test_vectorized.toarray())
# Evaluate the model
print("Accuracy:", accuracy_score(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))
#%% md
# From comparing the two models, we see that the LR model with accuracy of 0.79 is better than the NB model which has an accuracy of 0.77.
#%% md
# # Save best Model
#
#%%
output_file = f'model.bin'
#%%
# Save the model
with open(output_file, 'wb') as f_out:
pickle.dump((dv, lr_best), f_out)
print(f'the model is saved to {output_file}')
#%%