-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisualize.py
209 lines (180 loc) · 8.97 KB
/
visualize.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
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import missingno as msno
from mpl_toolkits.mplot3d import Axes3D # Required for 3d projection
from scipy.spatial import ConvexHull
from sklearn.decomposition import PCA, KernelPCA
class Visualize:
def __init__(self):
self.folder = 'viz'
self.random_state = 20
self.class_colours = np.array(['blue', 'red', 'green', 'darkviolet', 'lime', 'darkorange', 'goldenrod',
'cyan', 'silver', 'deepskyblue', 'mediumspringgreen', 'gold'])
self.class_markers = np.array(['.', '^', '1', 'p', 'd', 'P', '+', 'v', 'x', 'X', '4', 'H'])
def confusion_matrix(self, y, y_pred, title):
plt.clf()
df_confusion = pd.crosstab(y, y_pred)
plt.figure(figsize=(8, 8))
sns.heatmap(df_confusion, annot=True, annot_kws={"size": 14}, fmt='d', cmap='Greens', cbar=False)
plt.title(title, fontsize=16)
plt.xlabel('Predicted label', fontsize=12)
plt.ylabel('True label', fontsize=12)
plt.savefig(fname=self.fname('CM', title), dpi=300, format='png')
plt.show()
def correlation_heatmap(self, ds, title='Correlation Heatmap', drop=False):
corr = ds.corr()
plt.clf()
fig, ax = plt.subplots(figsize=(30, 30))
ax.set_title(title, size=16)
colormap = sns.diverging_palette(220, 10, as_cmap=True)
dropSelf = np.zeros_like(corr) # Drop self-correlations
dropSelf[np.triu_indices_from(dropSelf)] = True
sns.heatmap(corr, cmap=colormap, annot=True, fmt=".2f", mask=dropSelf, cbar=False)
plt.xticks(range(len(corr.columns)), corr.columns)
plt.yticks(range(len(corr.columns)), corr.columns)
plt.savefig(fname=self.fname('CorrHeatmap', title), dpi=300, format='png')
plt.show()
def pairplot(self, ds, cols, hue, title='Pairplot'):
plt.clf()
fig, ax = plt.subplots(figsize=(80, 80))
sns.pairplot(ds, vars=cols, hue=hue, palette='hls')
fig.subplots_adjust(top=1.5, bottom=0.08)
fig.suptitle(title, size=8, y=1.08)
plt.savefig(fname=self.fname('Pairplot', title), dpi=300, format='png')
plt.show()
def scatter(self, df, cola, colb, hue):
plt.clf()
df[hue] = df[hue].astype('category')
plt.figure(figsize=(10, 6))
title = '{} vs {} - Label {}'.format(cola, colb, hue)
plt.title(title, fontsize=16)
plt.xlabel(cola, fontsize=12)
plt.ylabel(colb, fontsize=12)
sns.scatterplot(x=cola, y=colb, hue=hue, palette='Set1', legend=False, size=30, alpha=0.4, data=df)
plt.savefig(fname=self.fname('Scatter', title), dpi=300, format='png')
plt.show()
def convex_hull(self, df, buckets, cola, colb, target):
cmap = plt.get_cmap('Set1')
plt.clf()
plt.figure(figsize=(10, 6))
title = '{} vs {} - Label {}'.format(cola, colb, target)
plt.title(title, fontsize=16)
plt.xlabel(cola, fontsize=12)
plt.ylabel(colb, fontsize=12)
for i in range(len(buckets)):
bucket = df[df[target] == buckets[i]]
bucket = bucket.iloc[:, [df.columns.get_loc(cola), df.columns.get_loc(colb)]].values
hull = ConvexHull(bucket)
hull_color = self.class_colours[i]
plt.scatter(bucket[:, 0], bucket[:, 1], label=buckets[i], c=self.class_colours[i], alpha=0.4)
for j in hull.simplices:
plt.plot(bucket[j, 0], bucket[j, 1], color=hull_color)
plt.legend()
plt.savefig(fname=self.fname('Convex Hull', title), dpi=300, format='png')
plt.show()
def kdeplot(self, title, df, cols):
plt.clf()
fig, ax = plt.subplots(figsize=(15, 8))
ax.set_title(title, fontsize=18)
ax.tick_params(axis='both', which='major', labelsize=14)
for col in cols:
sns.kdeplot(df[col], ax=ax)
plt.savefig(fname=self.fname('KDE', title), dpi=300, format='png')
plt.show()
def matrix_missing(self, sample_df, title):
missing_data_df = sample_df.columns[sample_df.isnull().any()].tolist()
msno.matrix(sample_df[missing_data_df], sparkline=False, fontsize=12, figsize=(30, 22))
plt.title(title, fontsize=20, y=1.08)
fig = plt.gcf()
plt.tight_layout()
plt.savefig(fname=self.fname('Nullity', title), dpi=300, format='png')
plt.show()
def bar_missing(self, sample_df, title):
missing_data_df = sample_df.columns[sample_df.isnull().any()].tolist()
msno.bar(sample_df[missing_data_df], color="black", log=False, figsize=(30, 22))
plt.title(title, fontsize=24, y=1.05)
fig = plt.gcf()
plt.savefig(fname=self.fname('Nullity', title), dpi=300, format='png')
plt.show()
def heat_missing(self, sample_df, title):
missing_data_df = sample_df.columns[sample_df.isnull().any()].tolist()
msno.heatmap(sample_df[missing_data_df], figsize=(20, 20))
plt.title(title, fontsize=24)
fig = plt.gcf()
plt.savefig(fname=self.fname('Nullity', title), dpi=300, format='png')
plt.show()
def scatter_clusters(self, df, n_clusters, y_clusters, col_idx, projection=None):
is_pca = True if 'pca' in col_idx else False
is_kernelpca = True if 'kpca' in col_idx else False
is_3d = True if projection == '3d' else False
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection=projection)
df_x = df
if is_pca:
n_comp = 3 if is_3d else 2
pca = PCA(n_components=n_comp, random_state=self.random_state)
df_x = pca.fit_transform(df_x)
if is_kernelpca:
n_comp = 3 if is_3d else 2
kernelpca = KernelPCA(n_components=n_comp, random_state=self.random_state)
df_x = kernelpca.fit_transform(df_x)
if isinstance(df_x, pd.DataFrame):
df_x = df_x.values
xlabel = 'PCA Feature 0' if is_pca else 'Kernel PCA Feature 0' if is_kernelpca else df.columns[col_idx[0]]
ylabel = 'PCA Feature 1' if is_pca else 'Kernel PCA Feature 1' if is_kernelpca else df.columns[col_idx[1]]
ax.set_xlabel(xlabel, fontsize=12)
ax.set_ylabel(ylabel, fontsize=12)
if is_3d:
title = '3D Cluster PCA' if is_pca else '3D Cluster Kernel PCA' if is_kernelpca else '3D Cluster no PCA'
zlabel = 'PCA Feature 2' if is_pca else 'Kernel PCA Feature 2' if is_kernelpca else df.columns[col_idx[2]]
ax.set_zlabel(zlabel, fontsize=12)
else:
title = '2D Cluster PCA' if is_pca else '2D Cluster Kernel PCA' if is_kernelpca else '2D Cluster no PCA'
title = title + ' - ' + str(n_clusters) + ' Clusters'
title_suffix = ''
if not is_pca and not is_kernelpca:
title_suffix = ' - ' + df.columns[col_idx[0]] + ' vs ' + df.columns[col_idx[1]]
if is_3d:
title_suffix = title_suffix + ' vs ' + df.columns[col_idx[2]]
title = title + title_suffix
if is_pca or is_kernelpca:
plt.title(title, fontsize=16)
else:
plt.title(title, fontsize=12)
# 2 clusters minimum
for c in range(n_clusters):
if is_3d:
ax.scatter(df_x[y_clusters == c, col_idx[0]], df_x[y_clusters == c, col_idx[1]],
df_x[y_clusters == c, col_idx[2]], alpha=0.2, edgecolors='none', s=20,
c=self.class_colours[c])
else:
ax.scatter(df_x[y_clusters == c, col_idx[0]], df_x[y_clusters == c, col_idx[1]], alpha=0.2,
edgecolors='none', s=20, c=self.class_colours[c])
plt.savefig(fname=self.fname('Scatter Cluster', title), dpi=300, format='png')
plt.show()
def boundary(self, x, y, clf, title, cola, colb):
plt.clf()
if isinstance(x, pd.DataFrame):
x_set, y_set = x.values, y
else:
x_set, y_set = x, y
x1, x2 = np.meshgrid(np.arange(start=x_set[:, 0].min() - 1, stop=x_set[:, 0].max() + 1, step=0.01),
np.arange(start=x_set[:, 1].min() - 1, stop=x_set[:, 1].max() + 1, step=0.01))
plt.contourf(x1, x2, clf.predict(np.array([x1.ravel(), x2.ravel()]).T).reshape(x1.shape),
alpha=0.4, cmap=plt.get_cmap('Set1'))
plt.xlim(x1.min(), x1.max())
plt.ylim(x2.min(), x2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(x_set[y_set == j, 0], x_set[y_set == j, 1],
c=self.class_colours[i], label=j)
title = '{} - {} vs {}'.format(title, cola, colb)
plt.title(title, fontsize=14)
plt.xlabel(cola, fontsize=12)
plt.ylabel(colb, fontsize=12)
plt.legend()
plt.savefig(fname=self.fname('Boundary', title), dpi=300, format='png')
plt.show()
def fname(self, prefix, title):
return '{}/{} - {}.png'.format(self.folder, prefix, title)