-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathplots.py
252 lines (200 loc) · 6.62 KB
/
plots.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
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn import tree
import collections
import seaborn as sns
import numpy as np
import pandas as pd
from matplotlib.colors import LinearSegmentedColormap
def set_plot_style():
sns.reset_orig()
plt.rcParams["figure.figsize"] = (12, 8)
plt.rcParams["font.size"] = 14
plt.rcParams["lines.linewidth"] = 2
plt.rcParams["xtick.labelsize"] = 13
plt.rcParams["ytick.labelsize"] = 13
plt.rcParams["axes.labelsize"] = 14
plt.rcParams["axes.titlesize"] = 14
plt.rcParams["legend.fontsize"] = 13
plt.rcParams["axes.spines.top"] = False
plt.rcParams["axes.spines.right"] = False
def twospirals(n_samples, noise=0.5):
"""
Returns the two spirals dataset.
"""
n = np.sqrt(np.random.rand(n_samples, 1)) * 360 * (2 * np.pi) / 360
d1x = -np.cos(n) * n + np.random.rand(n_samples, 1) * noise
d1y = np.sin(n) * n + np.random.rand(n_samples, 1) * noise
return (
np.vstack((np.hstack((d1x, d1y)), np.hstack((-d1x, -d1y)))),
np.hstack((np.zeros(n_samples), np.ones(n_samples))),
)
def draw_linear_regression_function(reg, ax=None, **kwargs):
if not ax:
ax = plt.gca()
if reg.coef_.ndim > 1:
b_1, b_2 = reg.coef_[0, :]
else:
b_1, b_2 = reg.coef_
b_0 = reg.intercept_
# solve the function y = b_0 + b_1*X_1 + b_2 * X_2 for X2
x_low, x_high = ax.get_xlim()
x1s = np.linspace(x_low, x_high)
x2s = (0.5 - b_0 - b_1 * x1s) / b_2
ax.plot(x1s, x2s, **kwargs)
def plot_3d_views(X, y, cmap=None):
from mpl_toolkits.mplot3d import Axes3D
if not cmap:
cmap = LinearSegmentedColormap.from_list(
"discrete", colors=[(0.8, 0.2, 0.3), (0.1, 0.8, 0.3), (0, 0.4, 0.8)], N=3
)
fig = plt.figure(figsize=(20, 20))
ax = fig.add_subplot(2, 2, 1, projection="3d")
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=cmap)
ax.set_xlabel("X1")
ax.set_ylabel("X2")
ax.set_zlabel("X3")
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_zticklabels([])
ax = fig.add_subplot(2, 2, 2, projection="3d")
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=cmap)
ax.view_init(0, 0)
ax.set_xlabel("X1")
ax.set_ylabel("X2")
ax.set_zlabel("X3")
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_zticklabels([])
ax = fig.add_subplot(2, 2, 3, projection="3d")
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=cmap)
ax.view_init(0, 90)
ax.set_xlabel("X1")
ax.set_ylabel("X2")
ax.set_zlabel("X3")
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_zticklabels([])
ax = fig.add_subplot(2, 2, 4, projection="3d")
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=cmap)
ax.view_init(90, 0)
ax.set_xlabel("X1")
ax.set_ylabel("X2")
ax.set_zlabel("X3")
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_zticklabels([])
plt.subplots_adjust(wspace=0.005, hspace=0.005)
def draw_tree(clf):
import pydotplus
d = tree.export_graphviz(clf, out_file=None, filled=True)
graph = pydotplus.graph_from_dot_data(d)
colors = ("red", "dodgerblue")
edges = collections.defaultdict(list)
for edge in graph.get_edge_list():
edges[edge.get_source()].append(int(edge.get_destination()))
for edge in edges:
edges[edge].sort()
for i in range(2):
dest = graph.get_node(str(edges[edge][i]))[0]
dest.set_fillcolor(colors[i])
return graph.create(format="png")
def draw_svm_decision_function(clf, ax=None, **kwargs):
if not ax:
ax = plt.gca()
x_low, x_high = ax.get_xlim()
y_low, y_high = ax.get_ylim()
x1 = np.linspace(x_low, x_high, 40)
x2 = np.linspace(y_low, y_high, 40)
X1, X2 = np.meshgrid(x1, x2)
xy = np.vstack([X1.ravel(), X2.ravel()]).T
# get the separating hyperplane
Z = clf.decision_function(xy).reshape(X1.shape)
# plot decision boundary and margins
label = kwargs.pop("label", "Decision Boundary")
cs = ax.contour(
X1, X2, Z, levels=[-1.0, 0, 1.0], linestyles=["--", "-", "--"], **kwargs
)
cs.collections[0].set_label(label)
plt.axis("off")
def draw_decision_boundaries(knn, ax=None, cmap="winter", alpha=0.07, **kwargs):
if not ax:
ax = plt.gca()
x_low, x_high = ax.get_xlim()
y_low, y_high = ax.get_ylim()
x1 = np.linspace(x_low, x_high, 100)
x2 = np.linspace(y_low, y_high, 100)
X1, X2 = np.meshgrid(x1, x2)
xy = np.vstack([X1.ravel(), X2.ravel()]).T
Z = knn.predict(xy).reshape(X1.shape)
label = kwargs.pop("label", "Decision Boundary")
# plot decision boundary and margins
cs = ax.contourf(X1, X2, Z, **kwargs, cmap=cmap, alpha=alpha)
cs.collections[0].set_label(label)
plt.axis("off")
def draw_decision_surface(clf, predictions, label=None):
ax = plt.gca()
x_low, x_high = ax.get_xlim()
y_low, y_high = ax.get_ylim()
x1 = np.linspace(x_low, x_high, 100)
x2 = np.linspace(y_low, y_high, 100)
X1, X2 = np.meshgrid(x1, x2)
xy = np.vstack([X1.ravel(), X2.ravel()]).T
Z = clf.predict_proba(xy)[:, 1].reshape(X1.shape)
plt.imshow(
Z,
extent=[x_low, x_high, y_low, y_high],
cmap="GnBu",
origin="lower",
vmin=0,
vmax=1,
)
plt.grid()
plt.colorbar(label=label)
plt.axis("off")
def plot_bars_and_confusion(
truth,
prediction,
axes=None,
vmin=None,
vmax=None,
cmap="RdPu",
title=None,
bar_color=None,
):
accuracy = accuracy_score(truth, prediction)
cm = confusion_matrix(truth, prediction)
if not isinstance(truth, pd.Series):
truth = pd.Series(truth)
if not isinstance(prediction, pd.Series):
prediction = pd.Series(prediction)
correct = pd.Series(truth.values == prediction.values)
truth.sort_index(inplace=True)
prediction.sort_index(inplace=True)
if not axes:
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
if not vmin:
vmin = cm.min()
if not vmax:
vmax = cm.max()
if not bar_color:
correct.value_counts().plot.barh(ax=axes[0])
else:
correct.value_counts().plot.barh(ax=axes[0], color=bar_color)
axes[0].text(150, 0.5, "Accuracy {:0.3f}".format(accuracy))
sns.heatmap(
cm,
annot=True,
fmt="d",
cmap=cmap,
xticklabels=["No", "Yes"],
yticklabels=["No", "Yes"],
ax=axes[1],
vmin=vmin,
vmax=vmax,
)
axes[1].set_ylabel("Actual")
axes[1].set_xlabel("Predicted")
if title:
plt.suptitle(title)