This repository was archived by the owner on Oct 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathMultiVarAnalytics.py
More file actions
338 lines (304 loc) · 14.3 KB
/
MultiVarAnalytics.py
File metadata and controls
338 lines (304 loc) · 14.3 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
import matplotlib.pyplot as plt
import matplotlib
import scipy.stats as stats
from statsmodels.graphics.mosaicplot import mosaic
import statsmodels.api as sm
from statsmodels.formula.api import ols
import pandas as pd
import numpy as np
import scipy
class InteractionAnalytics():
@staticmethod
def rank_associations(df, conf_dict, col1, col2, col3, Export):
try:
col2 = int(col2)
col3 = int(col3)
except:
pass
# Passed Variable is Numerical
if (col1 in conf_dict['NumericalColumns']) :
fig,(ax1,ax2) = plt.subplots(1, 2)
if len(conf_dict['NumericalColumns'])>1:
# Interaction with numerical variables
df2 = df[conf_dict['NumericalColumns']]
corrdf = df2.corr()
corrdf = abs(corrdf) # get the absolute values of correlations since negative correlations also matter
corrdf2 = corrdf[corrdf.index==col1].reset_index()[[each for each in corrdf.columns \
if col1 not in each]].unstack().sort_values(kind="quicksort",
ascending=False).head(col2)
corrdf2 = corrdf2.reset_index()
corrdf2.columns = ['level0','level1','rsq']
corrdf2.set_index('level0', inplace=True)
corrdf2[['rsq']].plot(kind='bar', ax=ax1)
ax1.legend().set_visible(False)
ax1.set_xlabel('Absolute Correlation')
ax1.set_title('Top {} Associated Numeric Variables'.format(str(col2)))
# Interaction with categorical variables
etasquared_dict = {}
if len(conf_dict['CategoricalColumns']) >= 1:
for each in conf_dict['CategoricalColumns']:
mod = ols('{} ~ C({})'.format(col1, each),data=df[[col1,each]],missing='drop').fit()
aov_table = sm.stats.anova_lm(mod, typ=1)
esq_sm = aov_table['sum_sq'][0]/(aov_table['sum_sq'][0]+aov_table['sum_sq'][1])
etasquared_dict[each] = esq_sm
topk_esq = pd.DataFrame.from_dict(etasquared_dict, orient='index').unstack().sort_values(\
kind = 'quicksort', ascending=False).head(col3).reset_index().set_index('level_1')
topk_esq.columns = ['level_0', 'EtaSquared']
topk_esq[['EtaSquared']].plot(kind='bar',ax=ax2)
ax2.legend().set_visible(False)
ax2.set_xlabel('Eta-squared values')
ax2.set_title('Top {} Associated Categoric Variables'.format(str(col2)))
# Passed Variable is Categorical
else:
#Interaction with numerical variables
fig,(ax1,ax2) = plt.subplots(1,2)
if len(conf_dict['NumericalColumns']) >= 1:
etasquared_dict = {}
for each in conf_dict['NumericalColumns']:
mod = ols('{} ~ C({})'.format(each, col1), data = df[[col1,each]]).fit()
aov_table = sm.stats.anova_lm(mod, typ=1)
esq_sm = aov_table['sum_sq'][0]/(aov_table['sum_sq'][0]+aov_table['sum_sq'][1])
etasquared_dict[each] = esq_sm
topk_esq = pd.DataFrame.from_dict(etasquared_dict, orient='index').unstack().sort_values(\
kind = 'quicksort', ascending=False).head(col2).reset_index().set_index('level_1')
topk_esq.columns = ['level_0','EtaSquared']
topk_esq[['EtaSquared']].plot(kind='bar',ax=ax1)
ax1.legend().set_visible(False)
ax1.set_xlabel('Eta-squared values')
ax1.set_title('Top {} Associated Numeric Variables'.format(str(col2)))
# Interaction with categorical variables
cramer_dict = {}
if len(conf_dict['CategoricalColumns'])>1:
for each in conf_dict['CategoricalColumns']:
if each !=col1:
tbl = pd.crosstab(df[col1], df[each])
chisq = stats.chi2_contingency(tbl, correction=False)[0]
try:
cramer = np.sqrt(chisq/sum(tbl))
except:
cramer = np.sqrt(chisq/tbl.as_matrix().sum())
pass
cramer_dict[each] = cramer
topk_cramer = pd.DataFrame.from_dict(cramer_dict, orient='index').unstack().sort_values(\
kind = 'quicksort', ascending=False).head(col3).reset_index().set_index('level_1')
topk_cramer.columns = ['level_0','CramersV']
topk_cramer[['CramersV']].plot(kind='bar',ax=ax2)
ax2.legend().set_visible(False)
ax2.set_xlabel("Cramer's V")
ax2.set_title('Top {} Associated Categoric Variables'.format(str(col2)))
@staticmethod
def NoLabels(x):
return ''
@staticmethod
def categorical_relations(df, filename, col1, col2, Export=False):
# print col1, col2
if col1 != col2:
df2 = df[(df[col1].isin(df[col1].value_counts().head(10).index.tolist()))&(df[col2].isin(df[col2].value_counts().head(10).index.tolist())) ]
df3 = pd.crosstab(df2[col1], df2[col2])
df3 = df3+1e-8
else:
df3 = pd.DataFrame(df[col1].value_counts())[:10]
fig,ax = plt.subplots()
fig,rects = mosaic(df3.unstack(),ax=ax, statistic=False, labelizer=InteractionAnalytics.NoLabels, label_rotation=30)
# print rects
ax.set_ylabel(col1)
ax.set_xlabel(col2)
ax.set_title('{} vs {}'.format(col1, col2) )
@staticmethod
def numerical_relations(df, col1, col2, Export=False):
from statsmodels.nonparametric.smoothers_lowess import lowess
x = df[col2]
y = df[col1]
f, ax = plt.subplots(1)
# lowess
ax.scatter(x, y, c='g', s=6)
lowess_results = lowess(y, x)#[:,1]
xs = lowess_results[:, 0]
ys = lowess_results[:, 1]
ax.plot(xs,ys,'red',linewidth=1)
#ols
fit = np.polyfit(x, y, 1)
fit1d = np.poly1d(fit)
ax.plot(x, fit1d(x), '--b')
ax.set_xlabel(col2)
ax.set_ylabel(col1)
corr = round(scipy.stats.pearsonr(x, y)[0], 6)
ax.set_title('{} vs {}, Correlation {}'.format(col1, col2, corr))
@staticmethod
def numerical_correlation(df, conf_dict, col1, Export=False):
from matplotlib.pyplot import quiver, colorbar, clim, matshow
df2 = df[conf_dict['NumericalColumns']].corr(method=col1)
col_names = list(df[conf_dict['NumericalColumns']].columns)
# print col_names
fig,ax = plt.subplots(1, 1)
m = ax.matshow(df2, cmap=matplotlib.pyplot.cm.coolwarm)
ax.grid(b=False)
fig.colorbar(m)
ax.set_xticklabels([' '] + col_names) #xticks extend the displayable area. Catering for this by adding a dummy value
ax.set_yticklabels([' '] + col_names)
#return df2
@staticmethod
def numerical_pca(df, conf_dict, col1, col2, col3, Export=False):
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
num_numeric = len(conf_dict['NumericalColumns'])
num_pca = num_numeric
xticklabels = ['']
for i in range(1,num_pca+1):
xticklabels+=['Comp'+str(i)]
xticklabels+=['']
df2 = df[conf_dict['NumericalColumns']]
X = StandardScaler().fit_transform(df2.values)
pca = PCA(n_components=num_pca)
pca.fit(X)
fig, (ax1,ax2) = plt.subplots(1, 2)
# print pca.explained_variance_ratio_
ax1.bar(np.arange(1,(num_numeric+1),1),pca.explained_variance_ratio_ )
ax1.set_ylabel('% Variance Explained')
ax1.set_xticklabels(xticklabels)
x_pca_index = int(col2) - 1
y_pca_index = int(col3) - 1
Y_pca = pd.DataFrame(pca.fit_transform(X))
Y_pca_labels = []
for i in range(1,num_pca+1):
Y_pca_labels.append('PC'+str(i))
Y_pca.columns = Y_pca_labels
Y_pca[col1] = df[col1]
colors_dict = {}
colors_list = ['r', 'y', 'c', 'y', 'k']
j = 0
for i in np.unique(df[col1]):
colors_dict[i] = colors_list[j]
j += 1
if j == len(colors_list):
j = 0
colordf = pd.DataFrame.from_dict(colors_dict, orient='index').reset_index()
colordf.columns = [col1, 'color']
merged_df = pd.merge(colordf,Y_pca)
# print merged_df.head()
grouped_df = merged_df.groupby(col1)
for name, group in grouped_df:
ax2.scatter(
group[Y_pca.columns[x_pca_index]], group[Y_pca.columns[y_pca_index]],label=name, # data
c=group['color'], # marker colour
# color='y',
marker='o', # marker shape
s=6 # marker size
)
ax2.set_xlabel(Y_pca.columns[x_pca_index])
ax2.set_ylabel(Y_pca.columns[y_pca_index])
ax2.legend(title=col1, fontsize=14)
@staticmethod
def nc_relation(df, conf_dict, col1, col2, col3=None, Export=False):
fig,ax = plt.subplots()
f = df[[col1,col2]].boxplot(by=col2, ax=ax)
mod = ols('{} ~ {}'.format(col1, col2), data=df[[col1, col2]]).fit()
aov_table = sm.stats.anova_lm(mod, typ=1)
p_val = round(aov_table['PR(>F)'][0], 6)
status = 'Passed'
color = 'blue'
if p_val < 0.05:
status = 'Rejected'
color = 'red'
# ax.set_ylabel(col1)
fig.suptitle('ho {} (p_value = {})'.format( status, p_val), color=color, fontsize=10)
#return p_val, status, color
@staticmethod
def pca_3d(df, conf_dict, col1, col2, col3=None, Export=False):
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from mpl_toolkits.mplot3d import Axes3D
df2 = df[conf_dict['NumericalColumns']]
X = StandardScaler().fit_transform(df2.values)
pca = PCA(n_components=4)
pca.fit(X)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.view_init(elev=10, azim=int(col2)) # elevation and angle
# ax.dist=10
Y_pca = pd.DataFrame(pca.fit_transform(X))
Y_pca.columns = ['PC1','PC2','PC3','PC4']
Y_pca[col1] = df[col1]
colors_dict = {}
colors_list = ['r', 'y', 'c', 'y', 'k']
j = 0
for i in np.unique(df[col1]):
colors_dict[i] = colors_list[j]
j += 1
if j == len(colors_list):
j = 0
colordf = pd.DataFrame.from_dict(colors_dict, orient='index').reset_index()
colordf.columns = [col1,'color']
merged_df = pd.merge(colordf,Y_pca)
# print merged_df.head()
grouped_df = merged_df.groupby(col1)
for name, group in grouped_df:
ax.scatter(
group['PC1'], group['PC2'], group['PC3'], label=name, # data
c = group['color'], # marker colour
# color='y',
marker = 'o', # marker shape
s=6 # marker size
)
ax.set_xlabel('PC1', labelpad=18)
ax.set_ylabel('PC2', labelpad=18)
ax.set_zlabel('PC3', labelpad=18)
ax.legend(title=col1, fontsize=10)
@staticmethod
def pca_3d_new(df, conf_dict, col1, col2, col3, col4, col5, Export=False):
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from mpl_toolkits.mplot3d import Axes3D
df2 = df[conf_dict['NumericalColumns']]
X = StandardScaler().fit_transform(df2.values)
num_numeric = len(conf_dict['NumericalColumns'])
pca = PCA(n_components=num_numeric)
pca.fit(X)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.view_init(elev=10, azim=int(col5)) # elevation and angle
Y_pca = pd.DataFrame(pca.fit_transform(X))
Y_pca_names = []
for i in range(1, num_numeric+1):
Y_pca_names.append('PC'+str(i))
Y_pca.columns = Y_pca_names
Y_pca[col1] = df[col1]
colors_dict = {}
colors_list = ['r', 'y', 'c', 'y', 'k']
j = 0
for i in np.unique(df[col1]):
colors_dict[i] = colors_list[j]
j += 1
if j == len(colors_list):
j = 0
colordf = pd.DataFrame.from_dict(colors_dict, orient='index').reset_index()
colordf.columns = [col1,'color']
merged_df = pd.merge(colordf,Y_pca)
grouped_df = merged_df.groupby(col1)
for name, group in grouped_df:
ax.scatter(
group[Y_pca_names[int(col2)-1]], group[Y_pca_names[int(col3)-1]], group[Y_pca_names[int(col4)-1]], label=name, # data
c = group['color'], # marker colour
# color='y',
marker = 'o', # marker shape
s=6 # marker size
)
ax.set_xlabel(Y_pca_names[int(col2)-1], labelpad=18)
ax.set_ylabel(Y_pca_names[int(col3)-1], labelpad=18)
ax.set_zlabel(Y_pca_names[int(col4)-1], labelpad=18)
ax.legend(title=col1, fontsize=10)
@staticmethod
def nnc_relation(df, conf_dict, col1, col2, col3, Export=False):
import itertools
markers = ['x', 'o', '^']
color = itertools.cycle(['r', 'y', 'c', 'y', 'k'])
groups = df[[col1, col2, col3]].groupby(col3)
# Plot
fig, ax = plt.subplots()
ax.margins(0.05)
#print groups
for (name, group), marker in zip(groups, itertools.cycle(markers)):
ax.plot(group[col1], group[col2], marker='o', linestyle='', ms=4, label=name)
ax.set_xlabel(col1)
ax.set_ylabel(col2)
ax.legend(numpoints=1, loc='best', title=col3)