-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__main__.py
More file actions
487 lines (414 loc) · 10 KB
/
__main__.py
File metadata and controls
487 lines (414 loc) · 10 KB
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# %% Imports and libraries [markdown]
"""
# Imports and library functions
"""
# %%
# %load_ext autoreload
# %autoreload 2
# %%
from dataclasses import dataclass
from functools import partial, reduce
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from pandas import DataFrame
from scipy.stats import pearsonr
from seaborn._core.typing import ColumnName
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.tree import plot_tree
from lib.chartSpecificData import survivalFrame
from lib.clean import (capOutliers, fillColumnNaWithMedian,
fillColumnNaWithMode, logTransform)
from lib.featureEngineering import addFamilyCountData, addIsAdult
from lib.numericConversion import (SexConversion, embarkedConverter,
sexConverter)
# %% [markdown]
"""
## Import The Data
"""
# %%
data: DataFrame = pd.read_csv(
"https://raw.githubusercontent.com/datasciencedojo/datasets/refs/heads/master/titanic.csv"
)
# %% Data Exploration [markdown]
"""
# Data Exploration part 1
"""
# %% [markdown]
"""
### Get the first few rows
"""
# %%
data.head()
# %% [markdown]
"""
### Get the last few rows
"""
# %%
data.tail()
# %% [markdown]
"""
### Get summary, data types, that sort of thing
"""
# %%
data.info()
# %% [markdown]
"""
### Get descriptive statistics
"""
# %%
data.describe()
# %% [markdown]
# ### Categorical value counts
#
# Explain difference between numerical and categorical
#
# ["Pclass", "Sex", "Embarked"]):
# %% [markdown]
"""
Pclass
"""
# %%
sns.countplot(x="Pclass", data=data)
plt.show()
# %% [markdown]
"""
Sex
"""
# %%
sns.countplot(x="Sex", data=data)
plt.show()
# %% [markdown]
"""
Embarked
"""
# %%
sns.countplot(x="Embarked", data=data)
plt.show()
# %% [markdown]
"""
### Get number of nulls
"""
# %%
data.isnull().sum()
# %% [markdown]
"""
Graph
"""
# %%
sns.heatmap(data.isnull(), cbar=False, yticklabels=False, cmap="viridis")
plt.title("Missing values (yellow = null)")
plt.show()
# %% [markdown]
"""
### Outliers
* Improve accuracy – Prevent extreme values from skewing results.
* Correct errors – Remove data entry or measurement mistakes.
* Stabilize statistics – Protect metrics like the mean from distortion.
* Improve model performance – Help algorithms perform more reliably.
"""
# %% [markdown]
"""
Age
"""
# %%
sns.boxplot(y="Age", data=data)
plt.show()
# %% [markdown]
"""
Fare
"""
# %%
sns.boxplot(y="Fare", data=data)
plt.show()
# %% [markdown]
"""
SibSp
"""
# %%
sns.boxplot(y="SibSp", data=data)
plt.show()
# %% [markdown]
"""
Parch
"""
# %%
sns.boxplot(y="Parch", data=data)
plt.show()
# %% [markdown]
"""
### ydataprofiler
"""
# %%
ProfileReport(data, title="Titanic Profiling Report")
# %% [markdown]
"""
## Compose
a function that enables functional composition
compose :: function, function, ... -> function
compose(f, g, h, i)(x) is equivalent to i(h(g(f(x))))
"""
# %%
def compose(*funcs):
return reduce(lambda f, g: lambda x: g(f(x)), funcs, lambda x: x)
# %% data Preprocessing [markdown]
"""
# Data Preprocessing
Here we are just getting rid of null values and dropping irrelevant data that we don't need
"""
# %%
cleanData = compose(
lambda df: fillColumnNaWithMedian(df, "Age"),
lambda df: fillColumnNaWithMedian(df, "Fare"),
lambda df: fillColumnNaWithMode(df, "Embarked"),
lambda df: df.drop(["Name", "Ticket", "Cabin"], axis=1),
lambda df: capOutliers(df, "Age"),
lambda df: capOutliers(df, "SibSp"),
lambda df: logTransform(df, "Fare"),
)
convertDataToNumeric = compose(sexConverter, embarkedConverter)
processedData = compose(cleanData, convertDataToNumeric)(data)
processedDataRows = len(processedData)
# %% [markdown]
"""
# Data Exploration Part II and Data Visualization
"""
# %% [markdown]
"""
### ydata profiler again because catagorical data sucks
"""
# %%
# ProfileReport(processedData, title="Titanic Profiling Report")
# %% [markdown]
"""
### Correlation Graph
"""
# %%
processedDataCorrMatrix = processedData.corr().round(3)
sns.heatmap(processedDataCorrMatrix, annot=True, cmap="coolwarm")
plt.title("Correlation Matrix")
plt.show()
# %% [markdown]
"""
### Pairplot
this is a way of looking at a lot of graphs quickly
"""
# %%
sns.pairplot(processedData, hue="Survived")
plt.show()
# %% [markdown]
"""
### Survival by Sex
"""
# %%
# We don't want to relable our axes
processedDataCategoricalSex = compose(cleanData, embarkedConverter)(data)
sns.countplot(x="Sex", data=processedDataCategoricalSex)
plt.show()
# well that sucks, both sexes are the same color
# %%
# luckily we can fix that with hue
sns.countplot(x="Sex", hue="Sex", data=processedDataCategoricalSex)
plt.show()
# %% [markdown]
"""
hue is actually really powerful. It enables us to break things down by other variables
"""
# %%
sns.countplot(x="Survived", hue="Sex", data=processedDataCategoricalSex)
plt.show()
# %% [markdown]
"""
### Survival by class
"""
# %%
sns.countplot(x="Survived", hue="Pclass", data=processedDataCategoricalSex)
plt.show()
# %% [markdown]
"""
you can even break it down by multiple things, although it requires some work
"""
# %%
sns.countplot(
x=processedDataCategoricalSex["Survived"],
hue=processedDataCategoricalSex[["Pclass", "Sex"]].apply(tuple, axis=1),
)
plt.show()
# %% [markdown]
"""
### Survival by age
"""
# %%
sns.lineplot(x="Survived", y="Age", hue="Sex", data=processedDataCategoricalSex)
plt.show()
# %% [markdown]
"""
That's a horrible way to display the data and doesn't really tell us anything
"""
# %%
sns.boxplot(x="Survived", y="Age", hue="Sex", data=processedDataCategoricalSex)
plt.show()
# %% [markdown]
"""
you can even overlay plots, admittedy thisn't isn't the best representation...
"""
# %%
sns.boxplot(x="Survived", y="Age", hue="Sex", data=processedDataCategoricalSex)
sns.stripplot(x="Survived", y="Age", hue="Sex", data=processedDataCategoricalSex)
plt.show()
# %% [markdown]
"""
### Survival of women by age
"""
# %% [markdown]
"""
You can create new plots that meet certain conditions by modifying your dataframe
"""
# %%
df = processedDataCategoricalSex[processedDataCategoricalSex["Sex"] == "female"]
sns.countplot(x="Age", hue="Survived", data=df)
plt.show()
# %% [markdown]
"""
That was unreadable, lets go back to the histogram
"""
# %%
df = processedDataCategoricalSex[processedDataCategoricalSex["Sex"] == "female"]
sns.histplot(x="Age", hue="Survived", data=df)
plt.show()
# %% [markdown]
"""
### Survival of men by age
"""
# %%
df = processedDataCategoricalSex[processedDataCategoricalSex["Sex"] == "male"]
sns.histplot(x="Age", hue="Survived", data=df)
plt.show()
# %% [markdown]
"""
### Survival of children by age
"""
# %%
df = processedDataCategoricalSex[processedDataCategoricalSex["Age"] < 18]
sns.histplot(x=df["Age"], hue=df["Survived"])
plt.show()
# %% [markdown]
"""
The data isn't really displayed quite how we want it. Things seem to be combined weirdly. lets try a count plot
"""
# %%
df = processedDataCategoricalSex[processedDataCategoricalSex["Age"] < 18]
sns.countplot(
x=df["Age"],
hue=df["Survived"],
)
plt.show()
# %% [markdown]
"""
No thats not right either, lets try modifying the histogram
"""
# %%
df = processedDataCategoricalSex[processedDataCategoricalSex["Age"] < 18]
sns.histplot(x=df["Age"], hue=df["Survived"], discrete=True)
plt.show()
# %% [markdown]
"""
The problem with looking at the children is that there simply isn't a lot of data.
We can still calculate what your chance of surviving as a child is compared to adults
"""
# %%
childDf = processedDataCategoricalSex[processedDataCategoricalSex["Age"] < 18]
adultDf = processedDataCategoricalSex[processedDataCategoricalSex["Age"] >= 18]
boyDf = childDf[childDf["Sex"] == "male"]
girlDf = childDf[childDf["Sex"] == "female"]
manDf = adultDf[adultDf["Sex"] == "male"]
womanDf = adultDf[adultDf["Sex"] == "female"]
survivalPercent = lambda df: df["Survived"].value_counts(normalize=True) * 100
survivalDict = {
"childSurvive": survivalPercent(childDf),
"adultSurvive": survivalPercent(adultDf),
"boySurvive": survivalPercent(boyDf),
"girlSurvive": survivalPercent(girlDf),
"manSurvive": survivalPercent(manDf),
"womanSurvive": survivalPercent(womanDf),
}
survivalDict
# %% [markdown]
"""
# Machine learning
"""
# %% [markdown]
"""
### Random Forest
"""
# %%
X = processedData.drop(["Survived"], axis=1)
y = processedData["Survived"]
randomState = 42
# splitting up the dataset for teesting
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.2, random_state=randomState
)
randomForest = RandomForestClassifier(n_estimators=100, random_state=randomState)
randomForest.fit(X_train, y_train)
y_pred = randomForest.predict(X_val)
accuracy = accuracy_score(y_val, y_pred)
print(f"Accuracy: {accuracy}")
# %% [markdown]
"""
### Fine Tuning
"""
# %%
paramGrid = {
"n_estimators": [100, 200, 300],
"max_features": ["auto", "sqrt", "log2"],
"max_depth": [4, 6, 8, 10],
"criterion": ["gini", "entropy"],
}
gridSearch = GridSearchCV(
estimator=randomForest, param_grid=paramGrid, cv=5, n_jobs=3, scoring="accuracy"
)
gridSearch.fit(X_train, y_train)
bestParams = gridSearch.best_params_
print(f"bestParams: {bestParams}")
# create new model with better parameters
randomForest2 = gridSearch.best_estimator_
# fit the model
randomForest2.fit(X_train, y_train)
y_pred = randomForest2.predict(X_val)
accuracy = accuracy_score(y_val, y_pred)
print(f"Accuracy: {accuracy}")
# %% [markdown]
"""
### visualize the model
"""
# %%
tree = randomForest.estimators_[0]
plt.figure(figsize=(20, 10))
plot_tree(
tree,
feature_names=X.columns,
class_names=True,
filled=True,
fontsize=6,
rounded=True,
)
plt.show()
# %%
testPassenger = pd.DataFrame.from_dict(
{
"PassengerId": [1],
"Pclass": [1],
"Sex": [1],
"Age": [42],
"SibSp": [1],
"Parch": [0],
"Fare": [30],
"Embarked": [2],
}
)
testPassengerPrediction = randomForest.predict(testPassenger)
print(testPassengerPrediction)