-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmytools.py
2903 lines (2430 loc) · 131 KB
/
mytools.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
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import matplotlib.pyplot as plt
import plotly.express as px
import seaborn as sns
import pandas as pd
import numpy as np
from math import ceil
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import geopandas as gpd
import matplotlib.patheffects as pe
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder, PolynomialFeatures, RobustScaler
from sklearn.preprocessing import OrdinalEncoder, MinMaxScaler, FunctionTransformer
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.linear_model import Ridge, Lasso
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, RandomForestClassifier
from category_encoders import JamesSteinEncoder
from sklearn.experimental import enable_halving_search_cv
from sklearn.tree import DecisionTreeClassifier, export_text, plot_tree
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.model_selection import RandomizedSearchCV, HalvingGridSearchCV, HalvingRandomSearchCV
from sklearn.metrics import mean_squared_error, mean_absolute_error
from sklearn.metrics import confusion_matrix, classification_report, roc_curve, precision_recall_curve
from sklearn.metrics import ConfusionMatrixDisplay, RocCurveDisplay
from sklearn.metrics import make_scorer, precision_score, recall_score, f1_score, roc_auc_score
from sklearn.metrics import accuracy_score
from sklearn.inspection import permutation_importance
from sklearn.impute import KNNImputer
from sklearn.pipeline import Pipeline
from sklearn.compose import make_column_transformer, ColumnTransformer
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.neighbors import NearestNeighbors
from sklearn.cluster import KMeans, DBSCAN
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from datetime import datetime
import time
from joblib import dump, load
import pytz
import os
import re
import collections
from scipy.stats import skew, kurtosis, iqr
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler
import warnings
def get_unique(df, n=20, sort='none', list=True, strip=False, count=False, percent=False, plot=False, cont=False):
"""
Version 0.2
Obtains unique values of all variables below a threshold number "n", and can display counts or percents
Parameters:
- df: dataframe that contains the variables you want to analyze
- n: int (default is 20). Maximum number of unique values to consider (avoid iterating continuous data)
- sort: str, optional (default='none'). Determines the sorting of unique values:
'none' will keep original order,
'name' will sort alphabetically/numerically,
'count' will sort by count of unique values (descending)
- list: boolean, optional (default=True). Shows the list of unique values
- strip: boolean, optional (default=False). True will remove single quotes in the variable names
- count: boolean, optional (default=False). True will show counts of each unique value
- percent: boolean, optional (default=False). True will show percentage of each unique value
- plot: boolean, optional (default=False). True will show a basic chart for each variable
- cont: boolean, optional (default=False). True will analyze variables over n as continuous
Returns: None
"""
# Calculate # of unique values for each variable in the dataframe
var_list = df.nunique(axis=0)
# Iterate through each categorical variable in the list below n
print(f"\nCATEGORICAL: Variables with unique values equal to or below: {n}")
for i in range(len(var_list)):
var_name = var_list.index[i]
unique_count = var_list[i]
# If unique value count is less than n, get the list of values, counts, percentages
if unique_count <= n:
number = df[var_name].value_counts(dropna=False)
perc = round(number / df.shape[0] * 100, 2)
# Copy the index to a column
orig = number.index
# Strip out the single quotes
name = [str(n) for n in number.index]
name = [n.strip('\'') for n in name]
# Store everything in dataframe uv for consistent access and sorting
uv = pd.DataFrame({'orig': orig, 'name': name, 'number': number, 'perc': perc})
# Sort the unique values by name or count, if specified
if sort == 'name':
uv = uv.sort_values(by='name', ascending=True)
elif sort == 'count':
uv = uv.sort_values(by='number', ascending=False)
elif sort == 'percent':
uv = uv.sort_values(by='perc', ascending=False)
# Print out the list of unique values for each variable
if list:
print(f"\n{var_name} has {unique_count} unique values:\n")
for w, x, y, z in uv.itertuples(index=False):
# Decide on to use stripped name or not
if strip:
w = x
# Put some spacing after the value names for readability
w_str = str(w)
w_pad_size = uv.name.str.len().max() + 7
w_pad = w_str + " " * (w_pad_size - len(w_str))
y_str = str(y)
y_pad_max = uv.number.max()
y_pad_max_str = str(y_pad_max)
y_pad_size = len(y_pad_max_str) + 3
y_pad = y_str + " " * (y_pad_size - len(y_str))
if count and percent:
print("\t" + str(w_pad) + str(y_pad) + str(z) + "%")
elif count:
print("\t" + str(w_pad) + str(y))
elif percent:
print("\t" + str(w_pad) + str(z) + "%")
else:
print("\t" + str(w))
# Plot countplot if plot=True
if plot:
print("\n")
if strip:
if sort == 'count':
sns.barplot(data=uv, x='name', y='number', order=uv.sort_values('number', ascending=False).name)
else:
sns.barplot(data=uv, x=uv.loc[0], y='number', order=uv.sort_values('name', ascending=True).name)
else:
if sort == 'count':
sns.barplot(data=uv, x='orig', y='number', order=uv.sort_values('number', ascending=False).orig)
else:
sns.barplot(data=uv, x='orig', y='number', order=uv.sort_values('orig', ascending=True).orig)
plt.title(var_name)
plt.xlabel('')
plt.ylabel('')
plt.xticks(rotation=45)
plt.show()
if cont:
# Iterate through each categorical variable in the list below n
print(f"\nCONTINUOUS: Variables with unique values greater than: {n}")
for i in range(len(var_list)):
var_name = var_list.index[i]
unique_count = var_list[i]
if unique_count > n:
print(f"\n{var_name} has {unique_count} unique values:\n")
print(var_name)
print(df[var_name].describe())
# Plot countplot if plot=True
if plot:
print("\n")
sns.histplot(data=df, x=var_name)
# plt.title(var_name)
# plt.xlabel('')
# plt.ylabel('')
# plt.xticks(rotation=45)
plt.show()
def plot_charts(df, plot_type='both', n=10, ncols=3, fig_width=20, subplot_height=4, rotation=45, strip=False,
cat_cols=None, cont_cols=None, dtype_check=True, sample_size=None):
"""
Version 0.2
Plot barplots for categorical columns, or histograms for continuous columns, in a grid of subplots.
Parameters:
- df: dataframe that contains the variables you want to analyze
- plot_type: string, optional (default='both'). Type of charts to plot: 'cat' for categorical, 'cont' for
continuous, 'both' for both
- n: int (default=20). Threshold of unique values for categorical (equal or below) vs. continuous (above)
- ncols: int, optional (default=3). The number of columns in the subplot grid.
- fig_width: int, optional (default=20). The width of the entire plot figure (not the subplot width)
- subplot_height: int, optional (default=4). The height of each subplot.
- rotation: int, optional (default=45). The rotation of the x-axis labels.
- strip: boolean, optional (default=False). Will strip single quotes from ends of column names
- cat_cols: list, optional (default=None). A list of column names to treat as categorical variables. If not
provided, inferred based on the unique count.
- cont_cols: list, optional (default=None). A list of column names to treat as continuous variables. If not
provided, inferred based on the unique count.
- dtype_check: boolean, optional (default=True). If True, consider only numeric types (int64, float64) for
continuous variables.
- sample_size: float or int, optional (default=None). If provided and less than 1, the fraction of the data to
sample. If greater than or equal to 1, the number of samples to draw.
Returns: None
"""
# Helper function to plot continuous variables
def plot_continuous(df, cols, ncols, fig_width, subplot_height, strip, sample_size):
nrows = ceil(len(cols) / ncols)
fig, axs = plt.subplots(nrows, ncols, figsize=(fig_width, nrows * subplot_height), constrained_layout=True)
axs = np.array(axs).ravel() # Ensure axs is always a 1D numpy array
# Loop through all continuous columns
for i, col in enumerate(cols):
if sample_size:
sample_count = int(len(df[col].dropna()) * sample_size) # Calculate number of samples
data = df[col].dropna().sample(sample_count)
else:
data = df[col].dropna()
if strip:
sns.stripplot(x=data, ax=axs[i])
else:
sns.histplot(data, ax=axs[i], kde=False)
axs[i].set_title(f'{col}', fontsize=20)
axs[i].tick_params(axis='x', rotation=rotation)
axs[i].set_xlabel('')
# Remove empty subplots
for empty_subplot in axs[len(cols):]:
empty_subplot.remove()
# Helper function to plot categorical variables
def plot_categorical(df, cols, ncols, fig_width, subplot_height, rotation, sample_size):
nrows = ceil(len(cols) / ncols)
fig, axs = plt.subplots(nrows, ncols, figsize=(fig_width, nrows * subplot_height), constrained_layout=True)
axs = np.array(axs).ravel() # Ensure axs is always a 1D numpy array
# Loop through all categorical columns
for i, col in enumerate(cols):
uv = df[col].value_counts().reset_index().rename(columns={col: 'name', 'count': 'number'})
uv['perc'] = uv['number'] / uv['number'].sum()
if sample_size:
uv = uv.sample(sample_size)
sns.barplot(data=uv, x='name', y='number', order=uv.sort_values('number', ascending=False).name, ax=axs[i])
axs[i].set_title(f'{col}', fontsize=20)
axs[i].tick_params(axis='x', rotation=rotation)
axs[i].set_ylabel('Count')
axs[i].set_xlabel('')
# Remove empty subplots
for empty_subplot in axs[len(cols):]:
empty_subplot.remove()
# Compute unique counts and identify categorical and continuous variables
unique_count = df.nunique()
if cat_cols is None:
cat_cols = unique_count[unique_count <= n].index.tolist()
if cont_cols is None:
cont_cols = unique_count[unique_count > n].index.tolist()
if dtype_check:
cont_cols = [col for col in cont_cols if df[col].dtype in ['int64', 'float64']]
if plot_type == 'cat' or plot_type == 'both':
plot_categorical(df, cat_cols, ncols, fig_width, subplot_height, rotation, sample_size)
if plot_type == 'cont' or plot_type == 'both':
plot_continuous(df, cont_cols, ncols, fig_width, subplot_height, strip, sample_size)
def plot_charts_with_hue(df, plot_type='both', n=10, ncols=3, fig_width=20, subplot_height=4, rotation=0,
cat_cols=None, cont_cols=None, dtype_check=True, sample_size=None, hue=None, color_discrete_map=None, normalize=False, kde=False, multiple='layer'):
"""
Version 0.1
Plot barplots for categorical columns, or histograms for continuous columns, in a grid of subplots.
Option to pass a 'hue' parameter to dimenions the plots by a variable/column of the dataframe.
Parameters:
- df: dataframe that contains the variables you want to analyze
- plot_type: string, optional (default='both'). Type of charts to plot: 'cat' for categorical, 'cont' for continuous, 'both' for both
- n: int (default=20). Threshold of unique values for categorical (equal or below) vs. continuous (above)
- ncols: int, optional (default=3). The number of columns in the subplot grid.
- fig_width: int, optional (default=20). The width of the entire plot figure (not the subplot width)
- subplot_height: int, optional (default=4). The height of each subplot.
- rotation: int, optional (default=45). The rotation of the x-axis labels.
- cat_cols: list, optional (default=None). A list of column names to treat as categorical variables. If not provided, inferred based on the unique count.
- cont_cols: list, optional (default=None). A list of column names to treat as continuous variables. If not provided, inferred based on the unique count.
- dtype_check: boolean, optional (default=True). If True, consider only numeric types (int64, float64) for continuous variables.
- sample_size: float or int, optional (default=None). If provided and less than 1, the fraction of the data to sample. If greater than or equal to 1, the number of samples to draw.
- hue: string, optional (default=None). Name of the column to dimension by passing as 'hue' to the Seaborn charts.
- color_discrete_map: name of array or array, optional (default=None). Pass a color mapping for the values in the 'hue' variable.
- normalize: boolean, optional (default=False). Set to True to normalize categorical plots and see proportions instead of counts
- kde: boolean, optional (default=False). Set to show KDE line on continuous countplots
- multiple: 'layer', 'dodge', 'stack', 'fill', optional (default='layer'). Choose how to handle hue variable when plotted on countplots
Returns: None
"""
def plot_categorical(df, cols, ncols, fig_width, subplot_height, rotation, sample_size, hue, color_discrete_map, normalize):
if sample_size:
df = df.sample(sample_size)
nplots = len(cols)
nrows = nplots//ncols
if nplots % ncols:
nrows += 1
fig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=(fig_width, nrows*subplot_height), constrained_layout=True)
if isinstance(axs, np.ndarray):
if len(axs.shape) > 1:
axs = axs.ravel()
else:
axs = [axs]
for i, col in enumerate(cols):
if normalize:
# Normalize the counts
df_copy = df.copy()
data = df_copy.groupby(col)[hue].value_counts(normalize=True).rename('proportion').reset_index()
sns.barplot(data=data, x=col, y='proportion', hue=hue, palette=color_discrete_map, ax=axs[i])
axs[i].set_ylabel('Proportion', fontsize=12)
else:
order = df[col].value_counts().index
sns.countplot(data=df, x=col, hue=hue, palette=color_discrete_map, ax=axs[i], order=order)
axs[i].set_ylabel('Count', fontsize=12)
axs[i].set_xlabel(' ', fontsize=12)
axs[i].set_title(col, fontsize=16, pad=10)
axs[i].tick_params(axis='x', rotation=rotation)
# Remove empty subplots
for empty_subplot in axs[nplots:]:
fig.delaxes(empty_subplot)
def plot_continuous(df, cols, ncols=3, fig_width=15, subplot_height=5, sample_size=None, hue=None, color_discrete_map=None, kde=False, multiple=multiple):
if sample_size:
df = df.sample(sample_size)
nplots = len(cols)
nrows = nplots//ncols
if nplots % ncols:
nrows += 1
fig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=(fig_width, nrows * subplot_height), constrained_layout=True)
if isinstance(axs, np.ndarray):
if len(axs.shape) > 1:
axs = axs.ravel()
else:
axs = [axs]
for i, col in enumerate(cols):
if hue is not None:
sns.histplot(data=df, x=col, hue=hue, palette=color_discrete_map, ax=axs[i], kde=kde, multiple=multiple)
else:
sns.histplot(data=df, x=col, ax=axs[i])
axs[i].set_title(col, fontsize=16, pad=10)
axs[i].set_ylabel('Count', fontsize=12)
axs[i].set_xlabel(' ', fontsize=12)
axs[i].tick_params(axis='x', rotation=rotation)
# Remove empty subplots
for empty_subplot in axs[nplots:]:
fig.delaxes(empty_subplot)
unique_count = df.nunique()
if cat_cols is None:
cat_cols = unique_count[unique_count <= n].index.tolist()
if hue in cat_cols:
cat_cols.remove(hue)
if cont_cols is None:
cont_cols = unique_count[unique_count > n].index.tolist()
if dtype_check:
cont_cols = [col for col in cont_cols if df[col].dtype in ['int64', 'float64']]
if plot_type == 'cat' or plot_type == 'both':
plot_categorical(df, cat_cols, ncols, fig_width, subplot_height, rotation, sample_size, hue, color_discrete_map, normalize)
if plot_type == 'cont' or plot_type == 'both':
plot_continuous(df, cont_cols, ncols, fig_width, subplot_height, sample_size, hue, color_discrete_map, kde, multiple)
def plot_corr(df, column, n, meth='pearson', size=(15, 8), rot=45, pal='RdYlGn', rnd=2):
"""
Version 0.2
Create a barplot that shows correlation values for one variable against others.
Essentially one slice of a heatmap, but the bars show the height of the correlation
in addition to the color. It will only look at numeric variables.
Parameters:
- df: dataframe that contains the variables you want to analyze
- column: string. Column name that you want to evaluate the correlations against
- n: int. The number of correlations to show (split evenly between positive and negative correlations)
- meth: optional (default='pearson'). See df.corr() method options
- size: tuple of ints, optional (default=(15, 8)). The size of the plot
- rot: int, optional (default=45). The rotation of the x-axis labels
- pal: string, optional (default='RdYlGn'). The color map to use
- rnd: int, optional (default=2). Number of decimal places to round to
Returns: None
"""
# Calculate correlations
corr = round(df.corr(method=meth, numeric_only=True)[column].sort_values(), rnd)
# Drop column from correlations (correlating with itself)
corr = corr.drop(column)
# Get the most negative and most positive correlations, sorted by absolute value
most_negative = corr.sort_values().head(n // 2)
most_positive = corr.sort_values().tail(n // 2)
# Concatenate these two series and sort the final series by correlation value
corr = pd.concat([most_negative, most_positive]).sort_values()
# Generate colors based on correlation values using a colormap
cmap = plt.get_cmap(pal)
colors = cmap((corr.values + 1) / 2)
# Plot the chart
plt.figure(figsize=size)
plt.axhline(y=0, color='lightgrey', alpha=0.8, linestyle='-')
bars = plt.bar(corr.index, corr.values, color=colors)
# Add value labels to the end of each bar
for bar in bars:
yval = bar.get_height()
if yval < 0:
plt.text(bar.get_x() + bar.get_width() / 3.0, yval - 0.05, yval, va='top')
else:
plt.text(bar.get_x() + bar.get_width() / 3.0, yval + 0.05, yval, va='bottom')
plt.title('Correlation with ' + column, fontsize=20)
plt.ylabel('Correlation', fontsize=14)
plt.xlabel('Other Variables', fontsize=14)
plt.xticks(rotation=rot)
plt.ylim(-1, 1)
plt.show()
def split_dataframe(df, n):
"""
Split a DataFrame into two based on the number of unique values in each column.
Parameters:
- df: DataFrame. The DataFrame to split.
- n: int. The maximum number of unique values for a column to be considered categorical.
Returns:
- df_cat: DataFrame. Contains the columns of df with n or fewer unique values.
- df_num: DataFrame. Contains the columns of df with more than n unique values.
"""
df_cat = pd.DataFrame()
df_num = pd.DataFrame()
for col in df.columns:
if df[col].nunique() <= n:
df_cat[col] = df[col]
else:
df_num[col] = df[col]
return df_cat, df_num
def thousands(x, pos):
"""
Format a number with thousands separators.
Parameters:
- x: float. The number to format.
- pos: int. The position of the number.
Returns:
- s: string. The formatted number.
"""
s = '{:0,d}'.format(int(x))
return s
def thousand_dollars(x, pos):
"""
Format a number with thousands separators.
Parameters:
- x: float. The number to format.
- pos: int. The position of the number.
Returns:
- s: string. The formatted number.
"""
s = '${:0,d}'.format(int(x))
return s
def visualize_kmeans(df, x_var, y_var, centers=3, iterations=100):
# Select centers at random
starting_centers = df.sample(centers).reset_index(drop=True)
# Make a list to hold the center values
center_values = [starting_centers[[x_var, y_var]].iloc[i].values for i in range(centers)]
plt.figure(figsize=(8, 5))
sns.scatterplot(data=df, x=x_var, y=y_var, palette='tab10')
plt.scatter(starting_centers[x_var], starting_centers[y_var], marker='*', s=400, c='red', edgecolor='black')
plt.title('Starting Centers')
plt.show()
# For each iteration
for i in range(iterations):
# Determine intercluster variance
dists = [np.linalg.norm(df[[x_var, y_var]] - center_values[j], axis=1)**2 for j in range(centers)]
dist_X = pd.DataFrame(np.array(dists).T, columns=['d' + str(j+1) for j in range(centers)])
# Make cluster assignments
df['Cluster Label'] = np.argmin(dist_X.values, axis=1)
# Update centroids
new_centers = df.groupby('Cluster Label').mean()
# Update the center values
center_values = [new_centers[[x_var, y_var]].iloc[j].values for j in range(centers)]
plt_title = 'Iteration ' + str(i+1)
plt.figure(figsize=(8, 5))
sns.scatterplot(data=df, x=x_var, y=y_var, hue='Cluster Label', palette='tab10')
plt.scatter(new_centers[x_var], new_centers[y_var], marker='*', s=400, c='red', edgecolor='black')
plt.title(plt_title)
plt.show()
return df
import seaborn as sns
import plotly.express as px
def plot_3d(df, x, y, z, color=None, color_map=None, scale='linear'):
"""
Create a 3D scatter plot using Plotly Express.
Parameters:
- df: DataFrame. The input dataframe.
- x: str. The column name to be used for the x-axis.
- y: str. The column name to be used for the y-axis.
- z: str. The column name to be used for the z-axis.
- color: str, optional (default=None). The column name to be used for color coding the points.
- color_map: list of str, optional (default=None). The color map to be used. If None, the seaborn default color palette will be used.
- scale: str, optional (default='linear'). The scale type for the axis. Use 'log' for logarithmic scale.
Returns: None
"""
if color_map is None:
color_map = sns.color_palette().as_hex()
fig = px.scatter_3d(df,
x=x,
y=y,
z=z,
color=color,
color_discrete_sequence=color_map,
height=600,
width=1000)
title_text = "{}, {}, {} by {}".format(x, y, z, color)
fig.update_layout(title={'text': title_text, 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'},
showlegend=True,
scene_camera=dict(up=dict(x=0, y=0, z=1),
center=dict(x=0, y=0, z=-0.1),
eye=dict(x=1.5, y=-1.4, z=0.5)),
margin=dict(l=0, r=0, b=0, t=0),
scene=dict(xaxis=dict(backgroundcolor='white',
color='black',
gridcolor='#f0f0f0',
title=x,
title_font=dict(size=10),
tickfont=dict(size=10),
type=scale),
yaxis=dict(backgroundcolor='white',
color='black',
gridcolor='#f0f0f0',
title=y,
title_font=dict(size=10),
tickfont=dict(size=10),
type=scale),
zaxis=dict(backgroundcolor='lightgrey',
color='black',
gridcolor='#f0f0f0',
title=z,
title_font=dict(size=10),
tickfont=dict(size=10),
type=scale)))
fig.update_traces(marker=dict(size=3, opacity=1, line=dict(color='black', width=0.1)))
fig.show()
def plot_map_ca(df, lon='Longitude', lat='Latitude', hue=None, size=None, size_range=(50, 200), title='Geographic Chart', dot_size=None, alpha=0.8, color_map=None, fig_size=(12, 12)):
"""
Version 0.1
Plots a geographic map of California with data points overlaid.
Parameters:
- df: DataFrame containing the data to be plotted
- lon: str, optional (default='Longitude'). Column name in `df` representing the longitude coordinates
- lat: str, optional (default='Latitude'). Column name in `df` representing the latitude coordinates
- hue: str, optional (default=None). Column name in `df` for color-coding the points
- size: str, optional (default=None). Column name in `df` to scale the size of points
- size_range: tuple, optional (default=(50, 200)). Range of sizes if the `size` parameter is used
- title: str, optional (default='Geographic Chart'). Title of the plot
- dot_size: int, optional (default=None). Size of all dots if you want them to be uniform
- alpha: float, optional (default=0.8). Transparency of the points
- color_map: colormap, optional (default=None). Colormap to be used if `hue` is specified
- fig_size: tuple, optional (default=(12, 12)). Size of the figure
Returns: None
"""
# Define the locations of major cities
large_ca_cities = {'Name': ['Fresno', 'Los Angeles', 'Sacramento', 'San Diego', 'San Francisco', 'San Jose'],
'Latitude': [36.746842, 34.052233, 38.581572, 32.715328, 37.774931, 37.339386],
'Longitude': [-119.772586, -118.243686, -121.494400, -117.157256, -122.419417, -121.894956],
'County': ['Fresno', 'Los Angeles', 'Sacramento', 'San Diego', 'San Francisco', 'Santa Clara']}
df_large_cities = pd.DataFrame(large_ca_cities)
# Create a figure that utilizes Cartopy
fig = plt.figure(figsize=fig_size)
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent([-125, -114, 32, 42])
# Add geographic details
ax.add_feature(cfeature.LAND, facecolor='white')
ax.add_feature(cfeature.OCEAN, facecolor='lightgrey', alpha=0.5)
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.STATES)
# Add county boundaries
counties = gpd.read_file('data/cb_2018_us_county_5m.shp')
counties_ca = counties[counties['STATEFP'] == '06']
counties_ca = counties_ca.to_crs("EPSG:4326")
for geometry in counties_ca['geometry']:
ax.add_geometries([geometry], crs=ccrs.PlateCarree(), edgecolor='grey', alpha=0.3, facecolor='none')
# Draw the scatterplot of data
if dot_size:
ax.scatter(df[lon], df[lat], s=dot_size, cmap=color_map, alpha=alpha, transform=ccrs.PlateCarree())
else:
sns.scatterplot(data=df, x=lon, y=lat, hue=hue, size=size, alpha=alpha, ax=ax, palette=color_map, sizes=size_range)
# Add cities
ax.scatter(df_large_cities['Longitude'], df_large_cities['Latitude'], transform=ccrs.PlateCarree(), edgecolor='black')
for x, y, label in zip(df_large_cities['Longitude'], df_large_cities['Latitude'], df_large_cities['Name']):
text = ax.text(x + 0.05, y + 0.05, label, transform=ccrs.PlateCarree(), fontsize=12, ha='left', fontname='Arial')
text.set_path_effects([pe.withStroke(linewidth=3, foreground='white')])
# Finish up the chart
ax.set_title(title, fontsize=18, pad=15)
ax.set_xlabel('Longitude', fontsize=14, labelpad=15)
ax.set_ylabel('Latitude', fontsize=14)
ax.gridlines(draw_labels=True, color='lightgrey', alpha=0.5)
plt.show()
def get_corr(df, n=5, var=None, show_results=True, return_arrays=False):
"""
Gets the top n positive and negative correlations in a dataframe. Returns them in two
arrays. By default, prints a summary of the top positive and negative correlations.
Parameters
----------
- df : pandas.DataFrame. The dataframe you wish to analyze for correlations
- n : int, default 5. The number of top positive and negative correlations to list.
- var : str, (optional) default None. The variable of interest. If provided, the function
will only show the top n positive and negative correlations for this variable.
- show_results : boolean, default True. Print the results.
- return_arrays : boolean, default False. If true, return arrays with column names
Returns: Tuple (if return_arrays == True)
- positive_variables: array of variable names involved in top n positive correlations
- negative_variables: array of variable names involved in top n negative correlations
"""
pd.set_option('display.expand_frame_repr', False)
corr = round(df.corr(numeric_only=True), 2)
# Unstack correlation matrix into a DataFrame
corr_df = corr.unstack().reset_index()
corr_df.columns = ['Variable 1', 'Variable 2', 'Correlation']
# If a variable is specified, filter to correlations involving that variable
if var is not None:
corr_df = corr_df[(corr_df['Variable 1'] == var) | (corr_df['Variable 2'] == var)]
# Remove self-correlations and duplicates
corr_df = corr_df[corr_df['Variable 1'] != corr_df['Variable 2']]
corr_df[['Variable 1', 'Variable 2']] = np.sort(corr_df[['Variable 1', 'Variable 2']], axis=1)
corr_df = corr_df.drop_duplicates(subset=['Variable 1', 'Variable 2'])
# Sort by absolute correlation value from highest to lowest
corr_df['AbsCorrelation'] = corr_df['Correlation'].abs()
corr_df = corr_df.sort_values(by='AbsCorrelation', ascending=False)
# Drop the absolute value column
corr_df = corr_df.drop(columns='AbsCorrelation').reset_index(drop=True)
# Get the first n positive and negative correlations
positive_corr = corr_df[corr_df['Correlation'] > 0].head(n).reset_index(drop=True)
negative_corr = corr_df[corr_df['Correlation'] < 0].head(n).reset_index(drop=True)
# Print the results
if show_results:
print("Top", n, "positive correlations:")
print(positive_corr)
print("\nTop", n, "negative correlations:")
print(negative_corr)
# Return the arrays
if return_arrays:
# Remove target variable from the arrays
positive_variables = positive_corr[['Variable 1', 'Variable 2']].values.flatten()
positive_variables = positive_variables[positive_variables != var]
negative_variables = negative_corr[['Variable 1', 'Variable 2']].values.flatten()
negative_variables = negative_variables[negative_variables != var]
return positive_variables, negative_variables
def sk_vif(exogs, data):
# Set a high threshold, e.g., 1e10, for very large VIFs
MAX_VIF = 1e10
vif_dict = {}
for exog in exogs:
not_exog = [i for i in exogs if i !=exog]
# split the dataset, one independent variable against all others
X, y = data[not_exog], data[exog]
# fit the model and obtain R^2
r_squared = LinearRegression().fit(X,y).score(X,y)
# compute the VIF, with a check for r_squared close to 1
if 1 - r_squared < 1e-5: # or some other small threshold that makes sense for your application
vif = MAX_VIF
else:
vif = 1/(1-r_squared)
vif_dict[exog] = vif
return pd.DataFrame({"VIF": vif_dict})
def calc_vif(X):
# Calculate Variance Inflation Factor (VIF) to find which features have mutlticollinearity
vif = pd.DataFrame()
vif['variables'] = X.columns
vif['VIF'] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]
return(vif.sort_values(by='VIF', ascending=False))
def calc_fpi(model, X, y, n_repeats=10, random_state=42):
# Calculate Feature Permutation Importance to find out which features have the most effect
r = permutation_importance(model, X, y, n_repeats=n_repeats, random_state=random_state)
return pd.DataFrame({"Variables": X.columns,
"Score Mean": r.importances_mean,
"Score Std": r.importances_std}).sort_values(by="Score Mean", ascending=False)
from sklearn import linear_model
# List of classes that support the .coef_ attribute
SUPPORTED_COEF_CLASSES = (
linear_model.LogisticRegression,
linear_model.LogisticRegressionCV,
linear_model.PassiveAggressiveClassifier,
linear_model.Perceptron,
linear_model.RidgeClassifier,
linear_model.RidgeClassifierCV,
linear_model.SGDClassifier,
linear_model.SGDOneClassSVM,
linear_model.LinearRegression,
linear_model.Ridge,
linear_model.RidgeCV,
linear_model.SGDRegressor,
linear_model.ElasticNet,
linear_model.ElasticNetCV,
linear_model.Lars,
linear_model.LarsCV,
linear_model.Lasso,
linear_model.LassoCV,
linear_model.LassoLars,
linear_model.LassoLarsCV,
linear_model.LassoLarsIC,
linear_model.OrthogonalMatchingPursuit,
linear_model.OrthogonalMatchingPursuitCV,
linear_model.ARDRegression,
linear_model.BayesianRidge,
linear_model.HuberRegressor,
linear_model.QuantileRegressor,
linear_model.RANSACRegressor,
linear_model.TheilSenRegressor
)
def supports_coef(estimator):
"""Check if estimator supports .coef_"""
return isinstance(estimator, SUPPORTED_COEF_CLASSES)
def extract_features_and_coefficients(grid_or_pipe, X, debug=False):
# Determine the type of the passed object and set flags
if hasattr(grid_or_pipe, 'best_estimator_'):
estimator = grid_or_pipe.best_estimator_
is_grid = True
is_pipe = False
if debug:
print('Grid: ', is_grid)
else:
estimator = grid_or_pipe
is_pipe = True
is_grid = False
if debug:
print('Pipe: ', is_pipe)
# Initial setup
current_features = list(X.columns)
if debug:
print('current_features: ', current_features)
mapping = pd.DataFrame({
'feature_name': current_features,
'intermediate_name1': current_features,
'selected': [True] * len(current_features),
'coefficients': [None] * len(current_features)
})
for step_name, step_transformer in estimator.named_steps.items():
if debug:
print(f"Processing step: {step_name} in {step_transformer}") # Debugging
n_features_in = len(current_features) # Number of features at the start of this step
# If transformer is a ColumnTransformer
if isinstance(step_transformer, ColumnTransformer):
new_features = [] # Collect new features from this step
step_transformer_list = step_transformer.transformers_
for name, trans, columns in step_transformer_list:
# OneHotEncoder or similar expanding transformers
if hasattr(trans, 'get_feature_names_out'):
out_features = list(trans.get_feature_names_out(columns))
new_features.extend(out_features)
else:
new_features.extend(columns)
current_features = new_features
# Update mapping based on current_features
mapping = pd.DataFrame({
'feature_name': current_features,
'intermediate_name1': current_features,
'selected': [True] * len(current_features),
'coefficients': [None] * len(current_features)
})
if debug:
print("Mapping: ", mapping)
# Reduction
elif hasattr(step_transformer, 'get_support'):
mask = step_transformer.get_support()
# Update selected column in mapping
mapping.loc[mapping['feature_name'].isin(current_features), 'selected'] = mask
current_features = mapping[mapping['selected']]['feature_name'].tolist()
# Inside your extract_features_and_coefficients function:
# If there's a model with coefficients in this step, update coefficients
if supports_coef(step_transformer):
coefficients = step_transformer.coef_.ravel()
selected_rows = mapping[mapping['selected']].index
if debug:
print("Coefficients: ", coefficients)
print(f"Number of coefficients: {len(coefficients)}") # Debugging
print(f"Number of selected rows: {len(selected_rows)}") # Debugging
if len(coefficients) == len(selected_rows):
mapping.loc[selected_rows, 'coefficients'] = coefficients.tolist()
else:
print(f"Mismatch in coefficients and selected rows for step: {step_name}")
# For transformers inside ColumnTransformer
if isinstance(step_transformer, ColumnTransformer):
if debug:
print("ColumnTransformer:", step_transformer)
transformers = step_transformer.transformers_
if debug:
print("Transformers: ", transformers)
new_features = [] # Collect new features from this step
for name, trans, columns in transformers:
# OneHotEncoder or similar expanding transformers
if hasattr(trans, 'get_feature_names_out'):
out_features = list(trans.get_feature_names_out(columns))
new_features.extend(out_features)
if debug:
print("Out features: ", out_features)
print("New features: ", new_features)
else:
new_features.extend(columns)
current_features = new_features
# Update mapping based on current_features
mapping = pd.DataFrame({
'feature_name': current_features,
'intermediate_name1': current_features,
'selected': [True] * len(current_features),
'coefficients': [None] * len(current_features)
})
if debug:
print("Mapping: ", mapping)
# Filtering the final selected features and their coefficients
final_data = mapping[mapping['selected']]
return final_data[['feature_name', 'coefficients']]
# MODEL ITERATION: default_config, create_pipeline, iterate_model
# default_config: Version 0.1
# Default configuration of parameters used by iterate_model and create_pipeline
# New configurations can be passed in by the user when function is called
#
# create_pipeline: Version 0.1
#
def create_pipeline(transformer_keys=None, scaler_key=None, selector_key=None, model_key=None, config=None, X_cat_columns=None, X_num_columns=None):
"""
Creates a pipeline for data preprocessing and modeling.
This function allows for flexibility in defining the preprocessing and
modeling steps of the pipeline. You can specify which transformers to apply
to the data, whether to scale the data, and which model to use for predictions.
If a step is not specified, it will be skipped.
Parameters:
- model_key (str): The key corresponding to the model in the config['models'] dictionary.
- transformer_keys (list of str, str, or None): The keys corresponding to the transformers
to apply to the data. This can be a list of string keys or a single string key corresponding
to transformers in the config['transformers'] dictionary. If not provided, no transformers will be applied.
- scaler_key (str or None): The key corresponding to the scaler to use to scale the data.
This can be a string key corresponding to a scaler in the config['scalers'] dictionary.
If not provided, the data will not be scaled.
- selector_key (str or None): The key corresponding to the feature selector.
This can be a string key corresponding to a scaler in the config['selectors'] dictionary.
If not provided, no feature selection will be performed.
- X_num_columns (list-like, optional): List of numeric columns from the input dataframe. This is used
in the default_config for the relevant transformers.
- X_cat_columns (list-like, optional): List of categorical columns from the input dataframe. This is used
in the default_config for the elevant encoders.
Returns:
pipeline (sklearn.pipeline.Pipeline): A scikit-learn pipeline consisting of the specified steps.
Example:
>>> pipeline = create_pipeline('linreg', transformer_keys=['ohe', 'poly2'], scaler_key='stand', config=my_config)
"""
# Check for configuration file parameter, if none, use default in library
if config is None:
# If no column lists are provided, raise an error
if not X_cat_columns and not X_num_columns:
raise ValueError("If no config is provided, X_cat_columns and X_num_columns must be passed.")
config = {
'transformers': {
'ohe': (OneHotEncoder(drop='if_binary', handle_unknown='ignore'), X_cat_columns),
'ord': (OrdinalEncoder(), X_cat_columns),
'js': (JamesSteinEncoder(), X_cat_columns),
'poly2': (PolynomialFeatures(degree=2, include_bias=False), X_num_columns),
'poly2_bias': (PolynomialFeatures(degree=2, include_bias=True), X_num_columns),
'poly3': (PolynomialFeatures(degree=3, include_bias=False), X_num_columns),
'poly3_bias': (PolynomialFeatures(degree=3, include_bias=True), X_num_columns),
'log': (FunctionTransformer(np.log1p, validate=True), X_num_columns)
},
'scalers': {
'stand': StandardScaler(),
'robust': RobustScaler(),
'minmax': MinMaxScaler()
},
'selectors': {
'sfs': SequentialFeatureSelector(LinearRegression()),
'sfs_7': SequentialFeatureSelector(LinearRegression(), n_features_to_select=7),
'sfs_6': SequentialFeatureSelector(LinearRegression(), n_features_to_select=6),
'sfs_5': SequentialFeatureSelector(LinearRegression(), n_features_to_select=5),
'sfs_4': SequentialFeatureSelector(LinearRegression(), n_features_to_select=4),
'sfs_3': SequentialFeatureSelector(LinearRegression(), n_features_to_select=3),
'sfs_bw': SequentialFeatureSelector(LinearRegression(), direction='backward')
},
'models': {
'linreg': LinearRegression(),
'ridge': Ridge(),
'lasso': Lasso(random_state=42),
'random_forest': RandomForestRegressor(),
'gradient_boost': GradientBoostingRegressor(),
}
}
# Initialize an empty list for the transformation steps
steps = []
# If transformers are provided, add them to the steps
if transformer_keys is not None:
transformer_steps = []
for key in (transformer_keys if isinstance(transformer_keys, list) else [transformer_keys]):
transformer, cols = config['transformers'][key]