-
Notifications
You must be signed in to change notification settings - Fork 340
/
Copy pathgen_samples.py
427 lines (356 loc) · 13.4 KB
/
gen_samples.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
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import graphviz
import graphviz.backend
from numpy.distutils.system_info import f2py_info
from sklearn import tree
from sklearn.datasets import load_boston, load_iris, load_wine, load_digits, load_breast_cancer, load_diabetes, fetch_mldata
from matplotlib.figure import figaspect
import string
import re
import matplotlib.pyplot as plt
import seaborn as sns
from dtreeviz.shadow import *
from numbers import Number
import matplotlib.patches as patches
from scipy import stats
from sklearn.neighbors import KernelDensity
import inspect
import sys
import tempfile
from dtreeviz.trees import *
"""
Generate samples into testing/samples dir to compare against future
images as a means of visually checking for errors.
Run with working directory as main dtreeviz dir so this code can see dtreeviz package
and data paths are set correctly.
"""
# REGRESSION
def viz_boston(orientation="TD",
max_depth=3,
random_state=666,
fancy=True,
pickX=False,
label_fontsize=12,
ticks_fontsize=8,
fontname="Arial"):
regr = tree.DecisionTreeRegressor(
max_depth=max_depth, random_state=random_state)
boston = load_boston()
regr.fit(boston.data, boston.target)
X = None
if pickX:
X = boston.data[np.random.randint(0, len(boston.data)), :]
if fontname == "TakaoPGothic":
feature_names = list(map(lambda x: f"特徴量{x}", boston.feature_names))
else:
feature_names = boston.feature_names
viz = dtreeviz(regr,
boston.data,
boston.target,
target_name='price',
feature_names=feature_names,
orientation=orientation,
fancy=fancy,
X=X,
label_fontsize=label_fontsize,
ticks_fontsize=ticks_fontsize,
fontname=fontname)
return viz
def viz_diabetes(orientation="TD",
max_depth=3,
random_state=666,
fancy=True,
pickX=False,
label_fontsize=12,
ticks_fontsize=8,
fontname="Arial"):
diabetes = load_diabetes()
regr = tree.DecisionTreeRegressor(
max_depth=max_depth, random_state=random_state)
regr.fit(diabetes.data, diabetes.target)
X = None
if pickX:
X = diabetes.data[np.random.randint(0, len(diabetes.data)), :]
viz = dtreeviz(regr,
diabetes.data,
diabetes.target,
target_name='progr',
feature_names=diabetes.feature_names,
orientation=orientation,
fancy=fancy,
X=X,
label_fontsize=label_fontsize,
ticks_fontsize=ticks_fontsize,
fontname=fontname)
return viz
def viz_sweets(orientation="TD",
max_depth=3,
random_state=666,
fancy=True,
pickX=False,
label_fontsize=12,
ticks_fontsize=8,
fontname="Arial"):
sweets = pd.read_csv("data/sweetrs.csv")
sweets = sweets.sample(n=500) # just grab 500 of 17k for plotting
X_train, y_train = sweets.drop('rating', axis=1), sweets['rating']
regr = tree.DecisionTreeRegressor(
max_depth=max_depth, random_state=random_state)
regr.fit(X_train, y_train)
X = None
if pickX:
X = X_train.iloc[np.random.randint(0, len(X_train))]
viz = dtreeviz(regr,
X_train,
y_train,
target_name='rating',
feature_names=sweets.columns,
orientation=orientation,
fancy=fancy,
X=X,
label_fontsize=label_fontsize,
ticks_fontsize=ticks_fontsize,
fontname=fontname)
return viz
def viz_fires(orientation="TD",
max_depth=3,
random_state=666,
fancy=True,
pickX=False,
label_fontsize=12,
ticks_fontsize=8,
fontname="Arial"):
fires = pd.read_csv("data/forestfires.csv")
fires['month'] = fires['month'].astype('category').cat.as_ordered()
fires['month'] = fires['month'].cat.codes + 1
fires['day'] = fires['day'].astype('category').cat.as_ordered()
fires['day'] = fires['day'].cat.codes + 1
X_train, y_train = fires.drop('area', axis=1), fires['area']
regr = tree.DecisionTreeRegressor(max_depth=max_depth,
random_state=random_state)
regr.fit(X_train, y_train)
X = None
if pickX:
X = X_train.iloc[np.random.randint(0, len(X_train))].values
viz = dtreeviz(regr,
X_train,
y_train,
target_name='area',
feature_names=fires.columns,
orientation=orientation,
fancy=fancy,
X=X,
label_fontsize=label_fontsize,
ticks_fontsize=ticks_fontsize,
fontname=fontname)
return viz
# CLASSIFICATION
def viz_iris(orientation="TD",
max_depth=3,
random_state=666,
fancy=True,
pickX=False,
label_fontsize=12,
ticks_fontsize=8,
fontname="Arial"):
clf = tree.DecisionTreeClassifier(
max_depth=max_depth, random_state=random_state)
iris = load_iris()
clf.fit(iris.data, iris.target)
if fontname == "TakaoPGothic":
feature_names = list(map(lambda x: f"特徴量{x}", iris.feature_names))
else:
feature_names = iris.feature_names
X = None
if pickX:
X = iris.data[np.random.randint(0, len(iris.data)), :]
viz = dtreeviz(clf,
iris.data,
iris.target,
target_name='variety',
feature_names=feature_names,
orientation=orientation,
class_names=["setosa",
"versicolor",
"virginica"], # 0,1,2 targets
fancy=fancy,
X=X,
label_fontsize=label_fontsize,
ticks_fontsize=ticks_fontsize,
fontname=fontname)
return viz
def viz_digits(orientation="TD",
max_depth=3,
random_state=666,
fancy=True,
pickX=False,
label_fontsize=12,
ticks_fontsize=8,
fontname="Arial"):
clf = tree.DecisionTreeClassifier(max_depth=max_depth,
random_state=random_state)
digits = load_digits()
# "8x8 image of integer pixels in the range 0..16."
columns = [f'pixel[{i},{j}]' for i in range(8) for j in range(8)]
clf.fit(digits.data, digits.target)
X = None
if pickX:
X = digits.data[np.random.randint(0, len(digits.data)), :]
viz = dtreeviz(clf,
digits.data,
digits.target,
target_name='number',
feature_names=columns,
orientation=orientation,
class_names=[chr(c) for c in range(ord('0'), ord('9')+1)],
fancy=fancy,
histtype='bar',
X=X,
label_fontsize=label_fontsize,
ticks_fontsize=ticks_fontsize,
fontname=fontname)
return viz
def viz_wine(orientation="TD",
max_depth=3,
random_state=666,
fancy=True,
pickX=False,
label_fontsize=12,
ticks_fontsize=8,
fontname="Arial"):
clf = tree.DecisionTreeClassifier(
max_depth=max_depth, random_state=random_state)
wine = load_wine()
clf.fit(wine.data, wine.target)
X = None
if pickX:
X = wine.data[np.random.randint(0, len(wine.data)), :]
viz = dtreeviz(clf,
wine.data,
wine.target,
target_name='wine',
feature_names=wine.feature_names,
orientation=orientation,
class_names=list(wine.target_names),
fancy=fancy,
X=X,
label_fontsize=label_fontsize,
ticks_fontsize=ticks_fontsize,
fontname=fontname)
return viz
def viz_breast_cancer(orientation="TD",
max_depth=3,
random_state=666,
fancy=True,
pickX=False,
label_fontsize=12,
ticks_fontsize=8,
fontname="Arial"):
clf = tree.DecisionTreeClassifier(
max_depth=max_depth, random_state=random_state)
cancer = load_breast_cancer()
clf.fit(cancer.data, cancer.target)
X = None
if pickX:
X = cancer.data[np.random.randint(0, len(cancer)), :]
viz = dtreeviz(clf,
cancer.data,
cancer.target,
target_name='cancer',
feature_names=cancer.feature_names,
orientation=orientation,
class_names=list(cancer.target_names),
fancy=fancy,
X=X,
label_fontsize=label_fontsize,
ticks_fontsize=ticks_fontsize,
fontname=fontname)
return viz
def viz_knowledge(orientation="TD",
max_depth=3,
random_state=666,
fancy=True,
pickX=False,
label_fontsize=12,
ticks_fontsize=8,
fontname="Arial"):
# data from https://archive.ics.uci.edu/ml/datasets/User+Knowledge+Modeling
clf = tree.DecisionTreeClassifier(max_depth=max_depth,
random_state=random_state)
know = pd.read_csv("data/knowledge.csv")
target_names = ['very_low', 'Low', 'Middle', 'High']
know['UNS'] = know['UNS'].map({n: i for i, n in enumerate(target_names)})
X_train, y_train = know.drop('UNS', axis=1), know['UNS']
clf.fit(X_train, y_train)
X = None
if pickX:
X = X_train.iloc[np.random.randint(0, len(know))]
viz = dtreeviz(clf,
X_train,
y_train,
target_name='UNS',
feature_names=X_train.columns.values,
orientation=orientation,
class_names=target_names,
fancy=fancy,
X=X,
label_fontsize=label_fontsize,
ticks_fontsize=ticks_fontsize,
fontname=fontname)
return viz
def save(name, dirname, orientation, max_depth, fancy=True, pickX=False, fontname="Arial"):
print(f"Process {name} orientation={orientation} max_depth={max_depth} fancy={fancy}, pickX={pickX}, fontname={fontname}")
viz = f(orientation=orientation,
max_depth=max_depth,
fancy=fancy,
pickX=pickX,
fontname=fontname)
X = "-X" if pickX else ""
filename = f"{name}-{orientation}-{max_depth}{X}-{fontname}"
if not fancy:
filename = filename+"-simple"
print(f"{dirname}/{filename}.svg")
viz.save(f"{dirname}/{filename}.svg")
# do it the hard way to set dpi for png
# g = graphviz.Source(st, format='png')
# filepath = g.save(filename=f"{filename}.dot", directory=tempfile.gettempdir()) # save dot file
# # cmd, rendered = graphviz.backend.command('dot', 'png', filepath)
# cmd = ['dot', '-Gdpi=300', '-Tpng', f'-o{dirname}/{filename}.png', filepath]
# graphviz.backend.run(cmd, capture_output=True, check=True, quiet=False)
# That conversion fails to get good image. do this on command line:
#
# $ convert -density 300x300 boston-TD-2.pdf foo.png
if __name__ == '__main__':
all_functions = inspect.getmembers(
sys.modules[__name__], inspect.isfunction)
these_functions = [t for t in all_functions if inspect.getmodule(
t[1]) == sys.modules[__name__]]
viz_funcs = [f[1] for f in these_functions if f[0].startswith('viz_')]
if len(sys.argv) > 1:
dirname = sys.argv[1]
else:
dirname = "."
print(f"tmp dir is {tempfile.gettempdir()}")
for f in viz_funcs:
name = f.__name__[len("viz_"):]
# if name!='sweets': continue
save(name, dirname, "TD", 2)
save(name, dirname, "TD", 4)
if name == 'iris':
save(name, dirname, "TD", 5)
save(name, dirname, "TD", 5, pickX=True)
save(name, dirname, "TD", 5, pickX=True, fontname="TakaoPGothic")
if name == 'boston':
# save(name, dirname, "TD", 3)
# save(name, dirname, "TD", 5, fancy=False, pickX=True)
# save(name, dirname, "LR", 5, fancy=False, pickX=True)
save(name, dirname, "LR", 5, fancy=False,
pickX=True, fontname="TakaoPGothic")
if name == 'knowledge':
save(name, dirname, "TD", 15, fancy=False, pickX=True)
save(name, dirname, "LR", 3)
save(name, dirname, "TD", 4, fancy=False)
save(name, dirname, "LR", 2, pickX=True)
save(name, dirname, "TD", 3, pickX=True)