/
criticisms.py
432 lines (358 loc) · 14.1 KB
/
criticisms.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
428
429
430
431
432
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import six
import tensorflow as tf
from edward.util import logit, get_dims, get_session
def evaluate(metrics, model, variational, data, y_true=None, n_samples=100):
"""Evaluate fitted model using a set of metrics.
Parameters
----------
metrics : list or str
List of metrics or a single metric.
model : ed.Model
Probability model p(x, z)
variational : ed.Variational
Variational approximation to the posterior p(z | x)
data : dict
Data dictionary to evaluate model with. For TensorFlow,
Python, and Stan models, the key type is a string; for PyMC3,
the key type is a Theano shared variable. For TensorFlow,
Python, and PyMC3 models, the value type is a NumPy array or
TensorFlow placeholder; for Stan, the value type is the type
according to the Stan program's data block.
y_true : np.ndarray or tf.Tensor
True values to compare to in supervised learning tasks.
n_samples : int, optional
Number of posterior samples for making predictions,
using the posterior predictive distribution.
Returns
-------
list or float
A list of evaluations or a single evaluation.
Raises
------
NotImplementedError
If an input metric does not match an implemented metric in Edward.
"""
sess = get_session()
# Monte Carlo estimate the mean of the posterior predictive:
# 1. Sample a batch of latent variables from posterior
zs = variational.sample(n_samples)
# 2. Make predictions, averaging over each sample of latent variables
y_pred = model.predict(data, zs)
# Evaluate y_pred according to y_true for all metrics.
evaluations = []
if isinstance(metrics, str):
metrics = [metrics]
for metric in metrics:
if metric == 'accuracy' or metric == 'crossentropy':
# automate binary or sparse cat depending on max(y_true)
support = tf.reduce_max(y_true).eval()
if support <= 1:
metric = 'binary_' + metric
else:
metric = 'sparse_categorical_' + metric
if metric == 'binary_accuracy':
evaluations += [sess.run(binary_accuracy(y_true, y_pred))]
elif metric == 'categorical_accuracy':
evaluations += [sess.run(categorical_accuracy(y_true, y_pred))]
elif metric == 'sparse_categorical_accuracy':
evaluations += [sess.run(sparse_categorical_accuracy(y_true, y_pred))]
elif metric == 'log_loss' or metric == 'binary_crossentropy':
evaluations += [sess.run(binary_crossentropy(y_true, y_pred))]
elif metric == 'categorical_crossentropy':
evaluations += [sess.run(categorical_crossentropy(y_true, y_pred))]
elif metric == 'sparse_categorical_crossentropy':
evaluations += [sess.run(sparse_categorical_crossentropy(y_true, y_pred))]
elif metric == 'hinge':
evaluations += [sess.run(hinge(y_true, y_pred))]
elif metric == 'squared_hinge':
evaluations += [sess.run(squared_hinge(y_true, y_pred))]
elif metric == 'mse' or metric == 'MSE' or \
metric == 'mean_squared_error':
evaluations += [sess.run(mean_squared_error(y_true, y_pred))]
elif metric == 'mae' or metric == 'MAE' or \
metric == 'mean_absolute_error':
evaluations += [sess.run(mean_absolute_error(y_true, y_pred))]
elif metric == 'mape' or metric == 'MAPE' or \
metric == 'mean_absolute_percentage_error':
evaluations += [sess.run(mean_absolute_percentage_error(y_true, y_pred))]
elif metric == 'msle' or metric == 'MSLE' or \
metric == 'mean_squared_logarithmic_error':
evaluations += [sess.run(mean_squared_logarithmic_error(y_true, y_pred))]
elif metric == 'poisson':
evaluations += [sess.run(poisson(y_true, y_pred))]
elif metric == 'cosine' or metric == 'cosine_proximity':
evaluations += [sess.run(cosine_proximity(y_true, y_pred))]
elif metric == 'log_lik' or metric == 'log_likelihood':
evaluations += [sess.run(y_pred)]
else:
raise NotImplementedError()
if len(evaluations) == 1:
return evaluations[0]
else:
return evaluations
def ppc(model, variational=None, data=None, T=None, n_samples=100):
"""Posterior predictive check.
(Rubin, 1984; Meng, 1994; Gelman, Meng, and Stern, 1996)
If no posterior approximation is provided through ``variational``,
then we default to a prior predictive check (Box, 1980).
PPC's form an empirical distribution for the predictive discrepancy,
.. math::
p(T) = \int p(T(xrep) | z) p(z | x) dz
by drawing replicated data sets xrep and calculating
:math:`T(xrep)` for each data set. Then it compares it to
:math:`T(x)`.
Parameters
----------
model : ed.Model
Class object that implements the ``sample_likelihood`` method
variational : ed.Variational, optional
Latent variable distribution q(z) to sample from. It is an
approximation to the posterior, e.g., a variational
approximation or an empirical distribution from MCMC samples.
If not specified, samples will be obtained from the model
through the ``sample_prior`` method.
data : dict, optional
Observed data to compare to. If not specified, will return
only the reference distribution with an assumed replicated
data set size of 1. For TensorFlow, Python, and Stan models,
the key type is a string; for PyMC3, the key type is a Theano
shared variable. For TensorFlow, Python, and PyMC3 models, the
value type is a NumPy array or TensorFlow placeholder; for
Stan, the value type is the type according to the Stan
program's data block.
T : function, optional
Discrepancy function, which takes a data dictionary and list
of latent variables as input and outputs a tf.Tensor. Default
is the identity function.
n_samples : int, optional
Number of replicated data sets.
Returns
-------
list
List containing the reference distribution, which is a Numpy
vector of size elements,
.. math::
(T(xrep^{1}, z^{1}), ..., T(xrep^{size}, z^{size}))
and the realized discrepancy, which is a NumPy vector of size
elements,
.. math::
(T(x, z^{1}), ..., T(x, z^{size})).
If the discrepancy function is not specified, then the list
contains the full data distribution where each element is a
data set (dictionary).
"""
sess = get_session()
if data is None:
N = 1
x = {}
else:
# Assume all values have the same data set size.
N = get_dims(list(six.itervalues(data))[0])[0]
x = data
# 1. Sample from posterior (or prior).
# We must fetch zs out of the session because sample_likelihood()
# may require a SciPy-based sampler.
if variational is not None:
zs = variational.sample(n_samples)
# This is to avoid fetching, e.g., a placeholder x with the
# dictionary {x: np.array()}. TensorFlow will raise an error.
if isinstance(zs, list):
zs = [tf.identity(zs_elem) for zs_elem in zs]
else:
zs = tf.identity(zs)
zs = sess.run(zs)
else:
zs = model.sample_prior(n_samples)
zs = zs.eval()
# 2. Sample from likelihood.
xreps = model.sample_likelihood(zs, N)
# 3. Calculate discrepancy.
if T is None:
if x is None:
return xreps
else:
return [xreps, y]
Txreps = []
Txs = []
for xrep, z in zip(yreps, tf.unpack(zs)):
Txreps += [T(xrep, z)]
if y is not None:
Txs += [T(x, z)]
if x is None:
return sess.run(tf.pack(Txreps))
else:
return sess.run([tf.pack(Txreps), tf.pack(Txs)])
# Classification metrics
def binary_accuracy(y_true, y_pred):
"""Binary prediction accuracy, also known as 0/1-loss.
Parameters
----------
y_true : tf.Tensor
Tensor of 0s and 1s.
y_pred : tf.Tensor
Tensor of probabilities.
"""
y_true = tf.cast(y_true, tf.float32)
y_pred = tf.cast(tf.round(y_pred), tf.float32)
return tf.reduce_mean(tf.cast(tf.equal(y_true, y_pred), tf.float32))
def categorical_accuracy(y_true, y_pred):
"""Multi-class prediction accuracy. One-hot representation for ``y_true``.
Parameters
----------
y_true : tf.Tensor
Tensor of 0s and 1s, where the outermost dimension of size ``K``
has only one 1 per row.
y_pred : tf.Tensor
Tensor of probabilities, with same shape as ``y_true``.
The outermost dimension denote the categorical probabilities for
that data point per row.
"""
y_true = tf.cast(tf.argmax(y_true, len(y_true.get_shape()) - 1), tf.float32)
y_pred = tf.cast(tf.argmax(y_pred, len(y_pred.get_shape()) - 1), tf.float32)
return tf.reduce_mean(tf.cast(tf.equal(y_true, y_pred), tf.float32))
def sparse_categorical_accuracy(y_true, y_pred):
"""Multi-class prediction accuracy. Label {0, 1, .., K-1}
representation for ``y_true``.
Parameters
----------
y_true : tf.Tensor
Tensor of integers {0, 1, ..., K-1}.
y_pred : tf.Tensor
Tensor of probabilities, with shape ``(y_true.get_shape(), K)``.
The outermost dimension are the categorical probabilities for
that data point.
"""
y_true = tf.cast(y_true, tf.float32)
y_pred = tf.cast(tf.argmax(y_pred, len(y_pred.get_shape()) - 1), tf.float32)
return tf.reduce_mean(tf.cast(tf.equal(y_true, y_pred), tf.float32))
def binary_crossentropy(y_true, y_pred):
"""Binary cross-entropy.
Parameters
----------
y_true : tf.Tensor
Tensor of 0s and 1s.
y_pred : tf.Tensor
Tensor of probabilities.
"""
y_true = tf.cast(y_true, tf.float32)
y_pred = logit(tf.cast(y_pred, tf.float32))
return tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(y_pred, y_true))
def categorical_crossentropy(y_true, y_pred):
"""Multi-class cross entropy. One-hot representation for ``y_true``.
Parameters
----------
y_true : tf.Tensor
Tensor of 0s and 1s, where the outermost dimension of size K
has only one 1 per row.
y_pred : tf.Tensor
Tensor of probabilities, with same shape as y_true.
The outermost dimension denote the categorical probabilities for
that data point per row.
"""
y_true = tf.cast(y_true, tf.float32)
y_pred = logit(tf.cast(y_pred, tf.float32))
return tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_pred, y_true))
def sparse_categorical_crossentropy(y_true, y_pred):
"""Multi-class cross entropy. Label {0, 1, .., K-1} representation
for ``y_true.``
Parameters
----------
y_true : tf.Tensor
Tensor of integers {0, 1, ..., K-1}.
y_pred : tf.Tensor
Tensor of probabilities, with shape ``(y_true.get_shape(), K)``.
The outermost dimension are the categorical probabilities for
that data point.
"""
y_true = tf.cast(y_true, tf.int64)
y_pred = logit(tf.cast(y_pred, tf.float32))
return tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(y_pred, y_true))
def hinge(y_true, y_pred):
"""Hinge loss.
Parameters
----------
y_true : tf.Tensor
Tensor of 0s and 1s.
y_pred : tf.Tensor
Tensor of real value.
"""
y_true = tf.cast(y_true, tf.float32)
y_pred = tf.cast(y_pred, tf.float32)
return tf.reduce_mean(tf.maximum(1.0 - y_true * y_pred, 0.0))
def squared_hinge(y_true, y_pred):
"""Squared hinge loss.
Parameters
----------
y_true : tf.Tensor
Tensor of 0s and 1s.
y_pred : tf.Tensor
Tensor of real value.
"""
y_true = tf.cast(y_true, tf.float32)
y_pred = tf.cast(y_pred, tf.float32)
return tf.reduce_mean(tf.square(tf.maximum(1.0 - y_true * y_pred, 0.0)))
# Regression metrics
def mean_squared_error(y_true, y_pred):
"""Mean squared error loss.
Parameters
----------
y_true : tf.Tensor
y_pred : tf.Tensor
Tensors of same shape and type.
"""
return tf.reduce_mean(tf.square(y_pred - y_true))
def mean_absolute_error(y_true, y_pred):
"""Mean absolute error loss.
Parameters
----------
y_true : tf.Tensor
y_pred : tf.Tensor
Tensors of same shape and type.
"""
return tf.reduce_mean(tf.abs(y_pred - y_true))
def mean_absolute_percentage_error(y_true, y_pred):
"""Mean absolute percentage error loss.
Parameters
----------
y_true : tf.Tensor
y_pred : tf.Tensor
Tensors of same shape and type.
"""
diff = tf.abs((y_true - y_pred) / tf.clip_by_value(tf.abs(y_true), 1e-8, np.inf))
return 100.0 * tf.reduce_mean(diff)
def mean_squared_logarithmic_error(y_true, y_pred):
"""Mean squared logarithmic error loss.
Parameters
----------
y_true : tf.Tensor
y_pred : tf.Tensor
Tensors of same shape and type.
"""
first_log = tf.log(tf.clip_by_value(y_pred, 1e-8, np.inf) + 1.0)
second_log = tf.log(tf.clip_by_value(y_true, 1e-8, np.inf) + 1.0)
return tf.reduce_mean(tf.square(first_log - second_log))
def poisson(y_true, y_pred):
"""Negative Poisson log-likelihood of data ``y_true`` given predictions
``y_pred`` (up to proportion).
Parameters
----------
y_true : tf.Tensor
y_pred : tf.Tensor
Tensors of same shape and type.
"""
return tf.reduce_sum(y_pred - y_true * tf.log(y_pred + 1e-8))
def cosine_proximity(y_true, y_pred):
"""Cosine similarity of two vectors.
Parameters
----------
y_true : tf.Tensor
y_pred : tf.Tensor
Tensors of same shape and type.
"""
y_true = tf.nn.l2_normalize(y_true, len(y_true.get_shape()) - 1)
y_pred = tf.nn.l2_normalize(y_pred, len(y_pred.get_shape()) - 1)
return tf.reduce_sum(y_true * y_pred)