-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpyroc.py
389 lines (309 loc) · 12.3 KB
/
pyroc.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
"""
Tools for working with ROC curves and the area under the ROC.
"""
__author__ = "Alistair Johnson <[email protected]>, Lucas Bulgarelli"
__version__ = "0.1.2"
from collections import OrderedDict
from collections.abc import Iterable
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm, chi2
class ROC(object):
"""Class for calculating receiver operator characteristic curves (ROCs).
Also facilitates statistically comparing the area under the ROC for
multiple predictors.
Attributes
----------
K : int
Calculated number of individual predictors.
n_obs : int
Calculated number of observations
n_pos : int
Number of observations with a positive class (== 1)
n_neg : int
Number of observations with a negative class (== 0)
X : np.ndarray
Numpy array of predictions for observations in the positive class
Y : np.ndarray
Numpy array of predictions for observations in the negative class
"""
def __init__(self, target, preds):
"""ROC class for comparing predictors for a common set of targets.
Parameters
----------
target : np.ndarray
A length N vector of binary values (0s or 1s).
preds
A vector of predictions which correspond to the targets
*or* a list of vectors,
*or* an NxD matrix,
*or* a dictionary of vectors.
"""
self.preds, self.target = self._parse_inputs(preds, target)
# TODO: validate that target/predictors work
# self._validate_inputs()
# initialize vars
self.K = len(self.preds)
self.n_obs = len(self.target)
self.n_pos = np.sum(self.target == 1)
self.n_neg = self.n_obs - self.n_pos
# First parse the predictions into matrices X and Y
# X: predictions for target = 1
# Y: predictions for target = 0
# Each prediction will be stored in a column of X and Y
# create "X" - the predictions when target == 1
idx = self.target == 1
self.X = np.zeros([self.n_pos, self.K])
for i, p in enumerate(self.preds.keys()):
self.X[:, i] = self.preds[p][idx]
# create "Y" - the predictions when target == 0
idx = ~idx
self.Y = np.zeros([self.n_neg, self.K])
for i, p in enumerate(self.preds.keys()):
self.Y[:, i] = self.preds[p][idx]
# calculate auc, V10, V01
self._calculate_auc()
# calculate S01, S10, S
self._calculate_covariance()
def _parse_inputs(self, preds, target):
"""Parse various formats of preds into dictionary/numpy array.
Parameters
----------
preds
A vector of predictions which correspond to the targets
*or* a list of vectors,
*or* an NxD matrix,
*or* a dictionary of vectors.
Returns
-------
(OrderedDict, np.ndarray)
- An ordered dictionary with the values for each predictor.
If no predictor names are provided, then predictor names are
monotonically increasing integers.
- A list of names for each predictor and a dictionary with
the values for each predictor. If no predictor names are
provided, then predictor names are monotonically increasing
integers.
"""
# Parse preds
if not isinstance(preds, dict):
parsed = np.asarray(preds)
# In case single list of predictions
if not isinstance(parsed[0], Iterable):
parsed = np.array([preds])
# If needed to transpose matrix
if parsed.shape[0] == len(target):
parsed = preds.T
# Use column names if it is a DataFrame
# Otherwise use increasing integers
if type(preds) == pd.DataFrame:
preds = zip(preds.columns, parsed.values)
else:
preds = enumerate(map(np.asarray, parsed))
# Finnally, ordered dictionary
preds = OrderedDict(preds)
# Parse target
if isinstance(target, Iterable):
target = np.asarray(target)
else:
raise TypeError('Target should be iterable, was %s', type(target))
# Ensure target is (N, ) length array, not (N, 1)
target = target.ravel()
return preds, target
def _calculate_auc(self):
"""Calculates the area under the ROC and the variances of each predictor.
"""
m = self.X.shape[0]
n = self.Y.shape[0]
theta = np.zeros([1, self.K])
V10 = np.zeros([m, self.K])
V01 = np.zeros([n, self.K])
for r in range(self.K): # For each X/Y column pair
# compare 0s to 1s
for i in range(m):
phi1 = np.sum(self.X[i, r] > self.Y[:, r])
# Xi > Y
phi2 = np.sum(self.X[i, r] == self.Y[:, r])
# Xi = Y
V10[i, r] = (phi1 + phi2 * 0.5) / n
theta[0, r] = theta[0, r] + phi1 + phi2 * 0.5
theta[0, r] = theta[0, r] / (n * m)
for j in range(n):
# correct classifications (X>Y)
phi1 = np.sum(self.X[:, r] > self.Y[j, r])
# ties (X==Y) get half points
phi2 = np.sum(self.X[:, r] == self.Y[j, r])
V01[j, r] = (phi1 + phi2 * 0.5) / m
self.auc = theta
self.V10 = V10
self.V01 = V01
return self.auc
def _calculate_covariance(self):
"""Calculate the covariance for K sets of predictions and outcomes
"""
m = self.V10.shape[0]
n = self.V01.shape[0]
if self.auc is None:
self._calculate_auc()
V01, V10, theta = self.V01, self.V10, self.auc
# Calculate S01 and S10, covariance matrices of V01 and V10
self.S01 = (
(np.transpose(V01) @ V01) - n * (np.transpose(theta) @ theta)
) / (n - 1)
self.S10 = (
(np.transpose(V10) @ V10) - m * (np.transpose(theta) @ theta)
) / (m - 1)
# Alternative equivalent formulations:
# self.S01 = (np.transpose(V01-theta)@(V01-theta))/(n-1)
# self.S10 = (np.transpose(V10-theta)@(V10-theta))/(m-1)
# self.S01 = np.cov(np.transpose(self.V01))
# self.S10 = np.cov(np.transpose(self.V10))
# Combine for S, covariance matrix of AUCs
self.S = (1 / m) * self.S10 + (1 / n) * self.S01
def ci(self, alpha=0.05):
"""Calculates the confidence intervals for each auroc separetely.
"""
if self.auc is None:
self._calculate_auc()
# Calculate CIs
itvs = np.transpose([[alpha / 2, 1 - (alpha / 2)]])
ci = norm.ppf(itvs, self.auc, np.sqrt(np.diagonal(self.S)))
return ci
def compare(self, contrast=None, alpha=0.05):
"""Compare predictions given a contrast
If no contrast is provided, and N classifiers are provided (C[0,N-1]),
all classifiers in C[1,N-1] is compared to C[0]
If there are two predictions, you can compare as:
roc.compare(contrast=[1, -1], alpha=0.05)
"""
# If no contrast is provided, and N classifiers are provided (C[0,N-1])
# compare classifiers C[1,N-1] to C[0]
if contrast is None:
contrast = -np.identity(self.K - 1)
contrast = np.insert(contrast, 0, np.ones(self.K - 1), axis=1)
# Validate alpha
if (alpha <= 0) | (alpha >= 1):
raise ValueError('alpha must be in the range (0, 1), exclusive.')
elif alpha > 0.5:
alpha = 1 - alpha
# Verify if covariance was calculated
if self.S is None:
self._calculate_covariance()
# L as matrix
L = np.array(contrast, dtype=float)
if len(L.shape) == 1:
L = L.reshape(1, L.shape[0])
# Shapes
L_sz = L.shape
S_sz = self.S.shape
# is not equal to number of classifiers
if (S_sz[1] != L_sz[1]): # Contrast column
raise ValueError(
'Contrast should have %d elements (number of predictors)',
S_sz[1]
)
# Validate contrast
if np.any(np.sum(L, axis=1) != 0):
raise ValueError('Contrast rows must sum to 0', S_sz[1])
# Calculate LSL matrix
LSL = L @ self.S @ np.transpose(L)
# Normal vs chi^2 distribution
if L_sz[0] == 1:
# Compute using the normal distribution
mu = L @ np.transpose(self.auc)
sigma = np.sqrt(LSL)
thetaP = norm.cdf(0, mu, sigma)
# 2-sided test, double the tails -> double the p-value
if mu < 0:
thetaP = 2 * (1 - thetaP)
else:
thetaP = 2 * thetaP
# Confidence intervals
theta2 = norm.ppf([alpha / 2, 1 - alpha / 2], mu, sigma)
else:
# Calculate chi2 stat with DOF = rank(L*S*L')
# first invert the LSL matrix
inv_LSL = np.linalg.inv(LSL)
# then calculate the chi2
w_chi2 = self.auc @ np.transpose(L) @ inv_LSL @ L @ np.transpose(
self.auc
)
w_df = np.linalg.matrix_rank(np.transpose(LSL))
thetaP = 1 - chi2.cdf(w_chi2, w_df)
theta2 = chi2.ppf([alpha / 2, 1 - alpha / 2], w_df)
return np.ndarray.item(thetaP), theta2
def _roc(self, pred):
"""Calculate false positive rate and true positive rate for ROC curve.
Returns
-------
(fpr, tpr)
np.ndarrays containing the false positive rate and the true
positive rate, respectively.
"""
# Transform to matrices
y_prob = np.array([pred])
target = np.array([self.target])
# Calculate predictions for all thresholds
thresholds = np.transpose([np.unique(y_prob)])
y_pred = np.greater_equal(y_prob, thresholds)
# FPR and TPR
P = target == 1
N = target == 0
FP = np.logical_and(y_pred == 1, N)
TP = np.logical_and(y_pred == 1, P)
fpr = np.sum(FP, axis=1) / np.sum(N)
tpr = np.sum(TP, axis=1) / np.sum(P)
return fpr, tpr
def __figure(self, figsize=(36, 30), **kwargs):
"""Initialize a figure for plotting the ROC curve.
"""
fig, ax = plt.subplots(figsize=figsize, **kwargs)
fig.tight_layout()
# Stylying
ax.tick_params(labelsize=60)
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
# Plot diagonal line
ax.plot([0, 1], [0, 1], color='black', lw=1, linestyle='--')
# Set axes limits
ax.set_xlim([-0.02, 1.0])
ax.set_ylim([-0.02, 1.05])
# Title and labels
ax.set_title('ROC Curve', fontsize=60)
ax.set_xlabel('False Positive Rate', fontsize=60)
ax.set_ylabel('True Positive Rate', fontsize=60)
# Adjust figure border
plt.gcf().subplots_adjust(top=0.97, bottom=0.06, left=0.07, right=0.98)
return (fig, ax)
def plot(self, labels=None, fontsize=50, **kwargs):
"""Plot the ROC curve.
"""
# Init figure with axes labels, etc.
fig, ax = self.__figure(**kwargs)
# Calculate auc
if self.auc is None:
self._calculate_auc()
# Calculate confidence intervals
ci = self.ci()
# Set default labels
if labels is None:
labels = self.preds.keys()
# Get colormap
viridis = plt.cm.get_cmap("viridis", len(labels))
for i, label in enumerate(labels):
# Get prediction for current iteration
pred = self.preds[label]
# Calculate FPRs and TPRs
fpr, tpr = self._roc(pred)
roc = ax.plot(fpr, tpr, lw=12, color=viridis(i))[0]
# Line legend
legend = '{0}, AUC = {1:0.2f} ({2:0.2f}-{3:0.2f})'.format(
label, self.auc[0, i], ci[0, i], ci[1, i]
)
roc.set_label(legend)
# Legend stylying
ax.legend(fontsize=fontsize, loc=4)
return (fig, ax)