-
Notifications
You must be signed in to change notification settings - Fork 169
/
wit-confusion-matrix.html
305 lines (284 loc) · 9.54 KB
/
wit-confusion-matrix.html
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
<!--
@license
Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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
http://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.
-->
<link rel="import" href="../tf-imports/polymer.html" />
<!-- Displays a simple confusion matrix. -->
<dom-module id="wit-confusion-matrix">
<template>
<style>
table {
display: inline-block;
}
td {
text-align: right;
}
th,
td {
font-size: 14px;
padding: 3px;
font-weight: normal;
}
.flex {
display: flex;
flex-direction: row-reverse;
}
.pred-label {
text-align: left;
font-size: 10px;
}
.total-label {
color: #5f6368;
font-size: 10px;
text-align: left;
}
.total-cell {
color: #5f6368;
}
.actual-label {
text-align: right;
font-size: 10px;
}
.n-label {
font-size: 10px;
vertical-align: bottom;
}
.value-cell {
color: #202124;
border: 1px solid lightgrey;
}
.parenthetical {
padding-right: 5px;
width: 50px;
}
</style>
<div id="holder"></div>
</template>
<script>
Polymer({
is: 'wit-confusion-matrix',
properties: {
/**
* Counts is a dictionary of dictionaries of numbers, representing
* the counts for each cell in a confusion matrix. The outermost keys
* represent actual labels and the innermost keys represent predicted
* labels. A number in this inner dictionary represents the count of
* elements with the prediction of the inner key and the actual label
* of the outer key.
* Example: {'No': {'Yes': 2, 'No': 1}, 'Yes': {'Yes': 3, 'No': 4}}
* contains 1 true negative, 2 false positives, 3 true positives and
* 4 false negatives.
*/
counts: Object,
/**
* Array where entries are all cell labels to be used in the
* confusion matrix. If empty, then the cell labels are extracted
* from the provided counts dictionary. This is used for when a
* confusion matrix should have more rows/columns that just the
* information from counts, such as in a multiclass problem where
* the counts do not contain information from all possible classes.
*/
allItems: {type: Array, value: () => []},
// Label appears in top-right corner of confusion matrix.
label: String,
// Color string for the base color to make the matrix cell
// backgrounds.
background: {
type: Object,
value: d3.color('gray'),
},
},
observers: ['drawMatrix(counts, allItems)'],
ready: function() {
// Allows d3-created elements in this Polymer element to be styled by
// the css rules above.
this.scopeSubtree(this.$.holder, true);
},
drawMatrix: function(counts, allItems) {
this.$.holder.innerHTML = '';
if (!counts) {
return;
}
// Get all labels from the provided list, or counts dict.
let labelsList = allItems;
if (labelsList == null || labelsList.length == 0) {
const labelsSet = new Set();
const outerLabelList = Object.keys(counts);
for (let i = 0; i < outerLabelList.length; i++) {
labelsSet.add(outerLabelList[i]);
const innerLabelList = Object.keys(counts[outerLabelList[i]]);
for (let j = 0; j < innerLabelList.length; j++) {
labelsSet.add(innerLabelList[j]);
}
}
labelsList = Array.from(labelsSet.values());
}
labelsList = labelsList.sort();
// For binary classification confusion matrices, we want the 'Yes'
// column/row to appear before 'No', so we reverse this labels list.
if (
labelsList.length == 2 &&
labelsList[0] == 'No' &&
labelsList[1] == 'Yes'
) {
labelsList = labelsList.reverse();
}
const columnTotals = new Array(labelsList.length);
_.fill(columnTotals, 0);
// Create the confusion matrix from the counts dict.
const countMatrix = [];
for (let i = 0; i < labelsList.length; i++) {
const arr = new Array(labelsList.length);
_.fill(arr, 0);
countMatrix.push(arr);
}
for (let i = 0; i < labelsList.length; i++) {
for (let j = 0; j < labelsList.length; j++) {
const actualLabel = labelsList[i];
const predLabel = labelsList[j];
if (actualLabel in counts && predLabel in counts[actualLabel]) {
countMatrix[i][j] = counts[actualLabel][predLabel];
}
}
}
// Pad the counts out to have objects of the correct size for the
// displayed matrix which contains a header row, header column, and
// footer rows and columns for the total counts.
const paddedCounts = [];
let total = 0;
for (let i = 0; i < countMatrix.length; i++) {
const rowTotal = countMatrix[i].reduce((a, b) => a + b, 0);
paddedCounts.push([0].concat(countMatrix[i]).concat([rowTotal]));
for (let j = 0; j < countMatrix.length; j++) {
columnTotals[j] += countMatrix[i][j];
total += countMatrix[i][j];
}
}
const indices = this.getIndices(countMatrix.length + 2);
// Create the table object.
const table = d3.select(this.$.holder).append('table');
const thead = table.append('thead');
const tbody = table.append('tbody');
const tfoot = table.append('tfoot');
// Set the header data.
thead
.append('tr')
.selectAll('th')
.data(indices)
.enter()
.append('th')
.text((column) => {
if (column == 0) {
return this.label;
} else if (column <= countMatrix.length) {
return 'Predicted ' + labelsList[column - 1];
} else {
return 'Total';
}
})
.attr('class', (column) => {
if (column == 0) {
return 'n-label';
} else if (column <= countMatrix.length) {
return 'pred-label';
} else {
return 'total-label';
}
});
// Set the confusion matrix rows.
const rows = tbody
.selectAll('tr')
.data(paddedCounts)
.enter()
.append('tr');
const cells = rows
.selectAll('td')
.data((row, j) => {
return row.map((entry, i) => {
if (i == 0) {
return {value: 'Actual ' + labelsList[j]};
} else {
return {value: entry, row: j};
}
});
})
.enter()
.append('td')
.attr('class', (d, i) => {
if (i == 0) {
return 'actual-label';
} else if (i <= countMatrix.length) {
return 'value-cell';
} else {
return 'total-cell';
}
})
.style('background', (d, i) => {
if (i == 0 || i > countMatrix.length) {
return '#FFFFFF';
} else {
let c = this.background;
c.opacity = d.value / total;
return c + '';
}
});
const cellDivs = cells.append('div').classed('flex', true);
cellDivs
.append('div')
.classed('parenthetical', (d, i) => !!i)
.text((d) => ('row' in d ? '(' + d.value + ')' : ''));
cellDivs
.append('div')
.text((d, i) =>
i > 0 ? d3.format(',.1%')(d.value / total) : d.value
);
// Set the footer row.
const footCells = tfoot
.append('tr')
.selectAll('td')
.data(indices)
.enter()
.append('td');
footCells.classed('total-label', (d, i) => i == 0);
footCells.classed('total-cell', (d, i) => i != 0);
const footCellDivs = footCells.append('div').classed('flex', true);
footCellDivs
.append('div')
.classed('parenthetical', (d, i) => !!i)
.text((column) => {
if (column == 0) {
return 'Total';
} else if (column <= countMatrix.length) {
return '(' + columnTotals[column - 1] + ')';
} else {
return '';
}
});
footCellDivs.append('div').text((column) => {
if (column == 0) {
return '';
} else if (column <= countMatrix.length) {
return d3.format(',.1%')(columnTotals[column - 1] / total);
} else {
return '';
}
});
},
/**
* Returns an list of indices from 0 to tableDim.
*/
getIndices: function(tableDim) {
return Array.apply(null, {length: tableDim}).map(Number.call, Number);
},
});
</script>
</dom-module>