-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmodel.html
More file actions
425 lines (369 loc) · 18.1 KB
/
model.html
File metadata and controls
425 lines (369 loc) · 18.1 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
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
<script src="https://d3js.org/d3.v6.min.js"></script>
<div id="tree_plot_74123ae4150b4273afc0b81cc553e49a"></div>
<script>
/*
* Copyright 2021 Google LLC.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Plotting of decision trees generated by TF-DF.
*
* A tree is a recursive structure of node objects.
* A node contains one or more of the following components:
*
* - A value: Representing the output of the node. If the node is not a leaf,
* the value is only present for analysis i.e. it is not used for
* predictions.
*
* - A condition : For non-leaf nodes, the condition (also known as split)
* defines a binary test to branch to the positive or negative child.
*
* - An explanation: Generally a plot showing the relation between the label
* and the condition to give insights about the effect of the condition.
*
* - Two children : For non-leaf nodes, the children nodes. The first
* children (i.e. "node.children[0]") is the negative children (drawn in
* red). The second children is the positive one (drawn in green).
*
*/
/**
* Plots a single decision tree into a DOM element.
* @param {!options} options Dictionary of configurations.
* @param {!tree} raw_tree Recursive tree structure.
* @param {string} canvas_id Id of the output dom element.
*/
function display_tree(options, raw_tree, canvas_id) {
console.log(options);
// Determine the node placement.
const tree_struct = d3.tree().nodeSize(
[options.node_y_offset, options.node_x_offset])(d3.hierarchy(raw_tree));
// Boundaries of the node placement.
let x_min = Infinity;
let x_max = -x_min;
let y_min = Infinity;
let y_max = -x_min;
tree_struct.each(d => {
if (d.x > x_max) x_max = d.x;
if (d.x < x_min) x_min = d.x;
if (d.y > y_max) y_max = d.y;
if (d.y < y_min) y_min = d.y;
});
// Size of the plot.
const width = y_max - y_min + options.node_x_size + options.margin * 2;
const height = x_max - x_min + options.node_y_size + options.margin * 2 +
options.node_y_offset - options.node_y_size;
const plot = d3.select(canvas_id);
// Tool tip
options.tooltip = plot.append('div')
.attr('width', 100)
.attr('height', 100)
.style('padding', '4px')
.style('background', '#fff')
.style('box-shadow', '4px 4px 0px rgba(0,0,0,0.1)')
.style('border', '1px solid black')
.style('font-family', 'sans-serif')
.style('font-size', options.font_size)
.style('position', 'absolute')
.style('z-index', '10')
.attr('pointer-events', 'none')
.style('display', 'none');
// Create canvas
const svg = plot.append('svg').attr('width', width).attr('height', height);
const graph =
svg.style('overflow', 'visible')
.append('g')
.attr('font-family', 'sans-serif')
.attr('font-size', options.font_size)
.attr(
'transform',
() => `translate(${options.margin},${
- x_min + options.node_y_offset / 2 + options.margin})`);
// Plot bounding box.
if (options.show_plot_bounding_box) {
svg.append('rect')
.attr('width', width)
.attr('height', height)
.attr('fill', 'none')
.attr('stroke-width', 1.0)
.attr('stroke', 'black');
}
// Draw the edges.
display_edges(options, graph, tree_struct);
// Draw the nodes.
display_nodes(options, graph, tree_struct);
}
/**
* Draw the nodes of the tree.
* @param {!options} options Dictionary of configurations.
* @param {!graph} graph D3 search handle containing the graph.
* @param {!tree_struct} tree_struct Structure of the tree (node placement,
* data, etc.).
*/
function display_nodes(options, graph, tree_struct) {
const nodes = graph.append('g')
.selectAll('g')
.data(tree_struct.descendants())
.join('g')
.attr('transform', d => `translate(${d.y},${d.x})`);
nodes.append('rect')
.attr('x', 0.5)
.attr('y', 0.5)
.attr('width', options.node_x_size)
.attr('height', options.node_y_size)
.attr('stroke', 'lightgrey')
.attr('stroke-width', 1)
.attr('fill', 'white')
.attr('y', -options.node_y_size / 2);
// Brackets on the right of condition nodes without children.
non_leaf_node_without_children =
nodes.filter(node => node.data.condition != null && node.children == null)
.append('g')
.attr('transform', `translate(${options.node_x_size},0)`);
non_leaf_node_without_children.append('path')
.attr('d', 'M0,0 C 10,0 0,10 10,10')
.attr('fill', 'none')
.attr('stroke-width', 1.0)
.attr('stroke', '#F00');
non_leaf_node_without_children.append('path')
.attr('d', 'M0,0 C 10,0 0,-10 10,-10')
.attr('fill', 'none')
.attr('stroke-width', 1.0)
.attr('stroke', '#0F0');
const node_content = nodes.append('g').attr(
'transform',
`translate(0,${options.node_padding - options.node_y_size / 2})`);
node_content.append(node => create_node_element(options, node));
}
/**
* Creates the D3 content for a single node.
* @param {!options} options Dictionary of configurations.
* @param {!node} node Node to draw.
* @return {!d3} D3 content.
*/
function create_node_element(options, node) {
// Output accumulator.
let output = {
// Content to draw.
content: d3.create('svg:g'),
// Vertical offset to the next element to draw.
vertical_offset: 0
};
// Conditions.
if (node.data.condition != null) {
display_condition(options, node.data.condition, output);
}
// Values.
if (node.data.value != null) {
display_value(options, node.data.value, output);
}
// Explanations.
if (node.data.explanation != null) {
display_explanation(options, node.data.explanation, output);
}
return output.content.node();
}
/**
* Adds a single line of text inside of a node.
* @param {!options} options Dictionary of configurations.
* @param {string} text Text to display.
* @param {!output} output Output display accumulator.
*/
function display_node_text(options, text, output) {
output.content.append('text')
.attr('x', options.node_padding)
.attr('y', output.vertical_offset)
.attr('alignment-baseline', 'hanging')
.text(text);
output.vertical_offset += 10;
}
/**
* Adds a single line of text inside of a node with a tooltip.
* @param {!options} options Dictionary of configurations.
* @param {string} text Text to display.
* @param {string} tooltip Text in the Tooltip.
* @param {!output} output Output display accumulator.
*/
function display_node_text_with_tooltip(options, text, tooltip, output) {
const item = output.content.append('text')
.attr('x', options.node_padding)
.attr('alignment-baseline', 'hanging')
.text(text);
add_tooltip(options, item, () => tooltip);
output.vertical_offset += 10;
}
/**
* Adds a tooltip to a dom element.
* @param {!options} options Dictionary of configurations.
* @param {!dom} target Dom element to equip with a tooltip.
* @param {!func} get_content Generates the html content of the tooltip.
*/
function add_tooltip(options, target, get_content) {
function show(d) {
options.tooltip.style('display', 'block');
options.tooltip.html(get_content());
}
function hide(d) {
options.tooltip.style('display', 'none');
}
function move(d) {
options.tooltip.style('display', 'block');
options.tooltip.style('left', (d.pageX + 5) + 'px');
options.tooltip.style('top', d.pageY + 'px');
}
target.on('mouseover', show);
target.on('mouseout', hide);
target.on('mousemove', move);
}
/**
* Adds a condition inside of a node.
* @param {!options} options Dictionary of configurations.
* @param {!condition} condition Condition to display.
* @param {!output} output Output display accumulator.
*/
function display_condition(options, condition, output) {
threshold_format = d3.format('r');
if (condition.type === 'IS_MISSING') {
display_node_text(options, `${condition.attribute} is missing`, output);
return;
}
if (condition.type === 'IS_TRUE') {
display_node_text(options, `${condition.attribute} is true`, output);
return;
}
if (condition.type === 'NUMERICAL_IS_HIGHER_THAN') {
format = d3.format('r');
display_node_text(
options,
`${condition.attribute} >= ${threshold_format(condition.threshold)}`,
output);
return;
}
if (condition.type === 'CATEGORICAL_IS_IN') {
display_node_text_with_tooltip(
options, `${condition.attribute} in [...]`,
`${condition.attribute} in [${condition.mask}]`, output);
return;
}
if (condition.type === 'CATEGORICAL_SET_CONTAINS') {
display_node_text_with_tooltip(
options, `${condition.attribute} intersect [...]`,
`${condition.attribute} intersect [${condition.mask}]`, output);
return;
}
if (condition.type === 'NUMERICAL_SPARSE_OBLIQUE') {
display_node_text_with_tooltip(
options, `Sparse oblique split...`,
`[${condition.attributes}]*[${condition.weights}]>=${
threshold_format(condition.threshold)}`,
output);
return;
}
display_node_text(
options, `Non supported condition ${condition.type}`, output);
}
/**
* Adds a value inside of a node.
* @param {!options} options Dictionary of configurations.
* @param {!value} value Value to display.
* @param {!output} output Output display accumulator.
*/
function display_value(options, value, output) {
if (value.type === 'PROBABILITY') {
const left_margin = 0;
const right_margin = 50;
const plot_width = options.node_x_size - options.node_padding * 2 -
left_margin - right_margin;
let cusum = Array.from(d3.cumsum(value.distribution));
cusum.unshift(0);
const distribution_plot = output.content.append('g').attr(
'transform', `translate(0,${output.vertical_offset + 0.5})`);
distribution_plot.selectAll('rect')
.data(value.distribution)
.join('rect')
.attr('height', 10)
.attr(
'x',
(d, i) =>
(cusum[i] * plot_width + left_margin + options.node_padding))
.attr('width', (d, i) => d * plot_width)
.style('fill', (d, i) => d3.schemeSet1[i]);
const num_examples =
output.content.append('g')
.attr('transform', `translate(0,${output.vertical_offset})`)
.append('text')
.attr('x', options.node_x_size - options.node_padding)
.attr('alignment-baseline', 'hanging')
.attr('text-anchor', 'end')
.text(`(${value.num_examples})`);
const distribution_details = d3.create('ul');
distribution_details.selectAll('li')
.data(value.distribution)
.join('li')
.append('span')
.text(
(d, i) =>
'class ' + i + ': ' + d3.format('.3%')(value.distribution[i]));
add_tooltip(options, distribution_plot, () => distribution_details.html());
add_tooltip(options, num_examples, () => 'Number of examples');
output.vertical_offset += 10;
return;
}
if (value.type === 'REGRESSION') {
display_node_text(
options,
'value: ' + d3.format('r')(value.value) + ` (` +
d3.format('.6')(value.num_examples) + `)`,
output);
return;
}
display_node_text(options, `Non supported value ${value.type}`, output);
}
/**
* Adds an explanation inside of a node.
* @param {!options} options Dictionary of configurations.
* @param {!explanation} explanation Explanation to display.
* @param {!output} output Output display accumulator.
*/
function display_explanation(options, explanation, output) {
// Margin before the explanation.
output.vertical_offset += 10;
display_node_text(
options, `Non supported explanation ${explanation.type}`, output);
}
/**
* Draw the edges of the tree.
* @param {!options} options Dictionary of configurations.
* @param {!graph} graph D3 search handle containing the graph.
* @param {!tree_struct} tree_struct Structure of the tree (node placement,
* data, etc.).
*/
function display_edges(options, graph, tree_struct) {
// Draw an edge between a parent and a child node with a bezier.
function draw_single_edge(d) {
return 'M' + (d.source.y + options.node_x_size) + ',' + d.source.x + ' C' +
(d.source.y + options.node_x_size + options.edge_rounding) + ',' +
d.source.x + ' ' + (d.target.y - options.edge_rounding) + ',' +
d.target.x + ' ' + d.target.y + ',' + d.target.x;
}
graph.append('g')
.attr('fill', 'none')
.attr('stroke-width', 1.2)
.selectAll('path')
.data(tree_struct.links())
.join('path')
.attr('d', draw_single_edge)
.attr(
'stroke', d => (d.target === d.source.children[0]) ? '#0F0' : '#F00');
}
display_tree({"margin": 10, "node_x_size": 160, "node_y_size": 28, "node_x_offset": 180, "node_y_offset": 33, "font_size": 10, "edge_rounding": 20, "node_padding": 2, "show_plot_bounding_box": false}, {"value": {"type": "PROBABILITY", "distribution": [0.660950339406931, 0.33904966059306896], "num_examples": 2799.0}, "condition": {"type": "CATEGORICAL_IS_IN", "attribute": "EmploymentDuration", "mask": ["4_to_7", "greater_7"]}, "children": [{"value": {"type": "PROBABILITY", "distribution": [0.4454828660436137, 0.5545171339563862], "num_examples": 1284.0}, "condition": {"type": "CATEGORICAL_IS_IN", "attribute": "CheckingStatus", "mask": ["no_checking", "greater_200"]}, "children": [{"value": {"type": "PROBABILITY", "distribution": [0.31934731934731936, 0.6806526806526807], "num_examples": 858.0}, "condition": {"type": "CATEGORICAL_IS_IN", "attribute": "Housing", "mask": ["free"]}, "children": [{"value": {"type": "PROBABILITY", "distribution": [0.18125, 0.81875], "num_examples": 320.0}, "condition": {"type": "NUMERICAL_IS_HIGHER_THAN", "attribute": "CurrentResidenceDuration", "threshold": 3.5}, "children": [{"value": {"type": "PROBABILITY", "distribution": [0.1232876712328767, 0.8767123287671232], "num_examples": 219.0}}, {"value": {"type": "PROBABILITY", "distribution": [0.3069306930693069, 0.693069306930693], "num_examples": 101.0}, "condition": {"type": "CATEGORICAL_IS_IN", "attribute": "OthersOnLoan", "mask": ["co-applicant", "guarantor"]}, "children": [{"value": {"type": "PROBABILITY", "distribution": [0.13333333333333333, 0.8666666666666667], "num_examples": 45.0}}, {"value": {"type": "PROBABILITY", "distribution": [0.44642857142857145, 0.5535714285714286], "num_examples": 56.0}, "condition": {"type": "NUMERICAL_IS_HIGHER_THAN", "attribute": "LoanAmount", "threshold": 4196.5}}]}]}, {"value": {"type": "PROBABILITY", "distribution": [0.40148698884758366, 0.5985130111524164], "num_examples": 538.0}, "condition": {"type": "NUMERICAL_IS_HIGHER_THAN", "attribute": "Age", "threshold": 54.5}, "children": [{"value": {"type": "PROBABILITY", "distribution": [0.058823529411764705, 0.9411764705882353], "num_examples": 34.0}}, {"value": {"type": "PROBABILITY", "distribution": [0.4246031746031746, 0.5753968253968254], "num_examples": 504.0}, "condition": {"type": "NUMERICAL_IS_HIGHER_THAN", "attribute": "ExistingCreditsCount", "threshold": 1.5}, "children": [{"value": {"type": "PROBABILITY", "distribution": [0.34824281150159747, 0.6517571884984026], "num_examples": 313.0}, "condition": {"type": "NUMERICAL_IS_HIGHER_THAN", "attribute": "LoanAmount", "threshold": 8185.0}}, {"value": {"type": "PROBABILITY", "distribution": [0.5497382198952879, 0.450261780104712], "num_examples": 191.0}, "condition": {"type": "CATEGORICAL_IS_IN", "attribute": "OwnsProperty", "mask": ["unknown"]}}]}]}]}, {"value": {"type": "PROBABILITY", "distribution": [0.6995305164319249, 0.3004694835680751], "num_examples": 426.0}}]}, {"value": {"type": "PROBABILITY", "distribution": [0.8435643564356435, 0.15643564356435644], "num_examples": 1515.0}, "condition": {"type": "CATEGORICAL_IS_IN", "attribute": "OwnsProperty", "mask": ["savings_insurance", "car_other", "unknown"]}, "children": [{"value": {"type": "PROBABILITY", "distribution": [0.7795753286147624, 0.2204246713852376], "num_examples": 989.0}, "condition": {"type": "NUMERICAL_IS_HIGHER_THAN", "attribute": "CurrentResidenceDuration", "threshold": 2.5}, "children": [{"value": {"type": "PROBABILITY", "distribution": [0.7099644128113879, 0.2900355871886121], "num_examples": 562.0}, "condition": {"type": "CATEGORICAL_IS_IN", "attribute": "OthersOnLoan", "mask": ["co-applicant", "guarantor"]}, "children": [{"value": {"type": "PROBABILITY", "distribution": [0.5, 0.5], "num_examples": 54.0}}, {"value": {"type": "PROBABILITY", "distribution": [0.7322834645669292, 0.2677165354330709], "num_examples": 508.0}, "condition": {"type": "NUMERICAL_IS_HIGHER_THAN", "attribute": "LoanDuration", "threshold": 20.5}, "children": [{"value": {"type": "PROBABILITY", "distribution": [0.6642335766423357, 0.3357664233576642], "num_examples": 274.0}, "condition": {"type": "CATEGORICAL_IS_IN", "attribute": "CheckingStatus", "mask": ["no_checking", "less_0", "greater_200"]}}, {"value": {"type": "PROBABILITY", "distribution": [0.811965811965812, 0.18803418803418803], "num_examples": 234.0}, "condition": {"type": "CATEGORICAL_IS_IN", "attribute": "EmploymentDuration", "mask": ["1_to_4", "unemployed"]}}]}]}, {"value": {"type": "PROBABILITY", "distribution": [0.8711943793911007, 0.1288056206088993], "num_examples": 427.0}}]}, {"value": {"type": "PROBABILITY", "distribution": [0.9638783269961977, 0.03612167300380228], "num_examples": 526.0}}]}]}, "#tree_plot_74123ae4150b4273afc0b81cc553e49a")
</script>