forked from scikit-learn/scikit-learn
/
metrics.py
2059 lines (1627 loc) · 66.5 KB
/
metrics.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""Utilities to evaluate the predictive performance of models
Functions named as ``*_score`` return a scalar value to maximize: the higher
the better
Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize:
the lower the better
"""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Mathieu Blondel <mathieu@mblondel.org>
# Olivier Grisel <olivier.grisel@ensta.org>
# Arnaud Joly <a.joly@ulg.ac.be>
# License: BSD 3 clause
from __future__ import division
import warnings
import numpy as np
from scipy.sparse import coo_matrix
from scipy.spatial.distance import hamming as sp_hamming
from ..externals.six.moves import zip
from ..preprocessing import LabelBinarizer
from ..utils import check_arrays
from ..utils import deprecated
from ..utils.fixes import divide
from ..utils.multiclass import is_label_indicator_matrix
from ..utils.multiclass import is_multilabel
from ..utils.multiclass import unique_labels
###############################################################################
# General utilities
###############################################################################
def _is_1d(x):
"""Return True if x can be considered as a 1d vector.
This function allows to distinguish between a 1d vector, e.g. :
- ``np.array([1, 2])``
- ``np.array([[1, 2]])``
- ``np.array([[1], [2]])``
and 2d matrix, e.g.:
- ``np.array([[1, 2], [3, 4]])``
Parameters
----------
x : numpy array.
Return
------
is_1d : boolean,
Return True if x can be considered as a 1d vector.
Examples
--------
>>> import numpy as np
>>> from sklearn.metrics.metrics import _is_1d
>>> _is_1d([1, 2, 3])
True
>>> _is_1d(np.array([1, 2, 3]))
True
>>> _is_1d([[1, 2, 3]])
True
>>> _is_1d(np.array([[1, 2, 3]]))
True
>>> _is_1d([[1], [2], [3]])
True
>>> _is_1d(np.array([[1], [2], [3]]))
True
>>> _is_1d([[1, 2], [3, 4]])
False
>>> _is_1d(np.array([[1, 2], [3, 4]]))
False
See also
--------
_check_1d_array
"""
return np.size(x) == np.max(np.shape(x))
def _check_1d_array(y1, y2, ravel=False):
"""Check that y1 and y2 are vectors of the same shape.
It convert 1d arrays (y1 and y2) of various shape to a common shape
representation. Note that ``y1`` and ``y2`` should have the same number of
elements.
Parameters
----------
y1 : array-like,
y1 must be a "vector".
y2 : array-like
y2 must be a "vector".
ravel : boolean, optional (default=False),
If ``ravel``` is set to ``True``, then ``y1`` and ``y2`` are raveled.
Returns
-------
y1 : numpy array,
If ``ravel`` is set to ``True``, return np.ravel(y1), else
return y1.
y2 : numpy array,
Return y2 reshaped to have the shape of y1.
Examples
--------
>>> from numpy import array
>>> from sklearn.metrics.metrics import _check_1d_array
>>> _check_1d_array([1, 2], [[3, 4]])
(array([1, 2]), array([3, 4]))
>>> _check_1d_array([[1, 2]], [[3], [4]])
(array([[1, 2]]), array([[3, 4]]))
>>> _check_1d_array([[1], [2]], [[3, 4]])
(array([[1],
[2]]), array([[3],
[4]]))
>>> _check_1d_array([[1], [2]], [[3, 4]], ravel=True)
(array([1, 2]), array([3, 4]))
See also
--------
_is_1d
"""
y1 = np.asarray(y1)
y2 = np.asarray(y2)
if not _is_1d(y1):
raise ValueError("y1 can't be considered as a vector")
if not _is_1d(y2):
raise ValueError("y2 can't be considered as a vector")
if ravel:
return np.ravel(y1), np.ravel(y2)
else:
if np.shape(y1) != np.shape(y2):
y2 = np.reshape(y2, np.shape(y1))
return y1, y2
def auc(x, y, reorder=False):
"""Compute Area Under the Curve (AUC) using the trapezoidal rule
This is a general fuction, given points on a curve. For computing the area
under the ROC-curve, see :func:`auc_score`.
Parameters
----------
x : array, shape = [n]
x coordinates.
y : array, shape = [n]
y coordinates.
reorder : boolean, optional (default=False)
If True, assume that the curve is ascending in the case of ties, as for
an ROC curve. If the curve is non-ascending, the result will be wrong.
Returns
-------
auc : float
Examples
--------
>>> import numpy as np
>>> from sklearn import metrics
>>> y = np.array([1, 1, 2, 2])
>>> pred = np.array([0.1, 0.4, 0.35, 0.8])
>>> fpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=2)
>>> metrics.auc(fpr, tpr)
0.75
See also
--------
auc_score : Computes the area under the ROC curve
"""
# XXX: Consider using ``scipy.integrate`` instead, or moving to
# ``utils.extmath``
x, y = check_arrays(x, y)
if x.shape[0] < 2:
raise ValueError('At least 2 points are needed to compute'
' area under curve, but x.shape = %s' % x.shape)
if reorder:
# reorder the data points according to the x axis and using y to
# break ties
x, y = np.array(sorted(points for points in zip(x, y))).T
h = np.diff(x)
else:
h = np.diff(x)
if np.any(h < 0):
h *= -1
assert not np.any(h < 0), ("Reordering is not turned on, and "
"The x array is not increasing: %s" % x)
area = np.sum(h * (y[1:] + y[:-1])) / 2.0
return area
###############################################################################
# Binary classification loss
###############################################################################
def hinge_loss(y_true, pred_decision, pos_label=1, neg_label=-1):
"""Average hinge loss (non-regularized)
Assuming labels in y_true are encoded with +1 and -1, when a prediction
mistake is made, ``margin = y_true * pred_decision`` is always negative
(since the signs disagree), implying ``1 - margin`` is always greater than
1. The cumulated hinge loss is therefore an upper bound of the number of
mistakes made by the classifier.
Parameters
----------
y_true : array, shape = [n_samples]
True target (integers).
pred_decision : array, shape = [n_samples] or [n_samples, n_classes]
Predicted decisions, as output by decision_function (floats).
Returns
-------
loss : float
References
----------
.. [1] `Wikipedia entry on the Hinge loss
<http://en.wikipedia.org/wiki/Hinge_loss>`_
Examples
--------
>>> from sklearn import svm
>>> from sklearn.metrics import hinge_loss
>>> X = [[0], [1]]
>>> y = [-1, 1]
>>> est = svm.LinearSVC(random_state=0)
>>> est.fit(X, y)
LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True,
intercept_scaling=1, loss='l2', multi_class='ovr', penalty='l2',
random_state=0, tol=0.0001, verbose=0)
>>> pred_decision = est.decision_function([[-2], [3], [0.5]])
>>> pred_decision # doctest: +ELLIPSIS
array([-2.18..., 2.36..., 0.09...])
>>> hinge_loss([-1, 1, 1], pred_decision) # doctest: +ELLIPSIS
0.30...
"""
# TODO: multi-class hinge-loss
if pos_label != 1 or neg_label != -1:
# the rest of the code assumes that positive and negative labels
# are encoded as +1 and -1 respectively
y_true = y_true.copy()
y_true[y_true == pos_label] = 1
y_true[y_true == neg_label] = -1
margin = y_true * pred_decision
losses = 1 - margin
# The hinge doesn't penalize good enough predictions.
losses[losses <= 0] = 0
return np.mean(losses)
###############################################################################
# Binary classification scores
###############################################################################
def average_precision_score(y_true, y_score):
"""Compute average precision (AP) from prediction scores
This score corresponds to the area under the precision-recall curve.
Note: this implementation is restricted to the binary classification task.
Parameters
----------
y_true : array, shape = [n_samples]
True binary labels.
y_score : array, shape = [n_samples]
Target scores, can either be probability estimates of the positive
class, confidence values, or binary decisions.
Returns
-------
average_precision : float
References
----------
.. [1] `Wikipedia entry for the Average precision
<http://en.wikipedia.org/wiki/Information_retrieval#Average_precision>`_
See also
--------
auc_score : Area under the ROC curve
precision_recall_curve :
Compute precision-recall pairs for different probability thresholds
Examples
--------
>>> import numpy as np
>>> from sklearn.metrics import average_precision_score
>>> y_true = np.array([0, 0, 1, 1])
>>> y_scores = np.array([0.1, 0.4, 0.35, 0.8])
>>> average_precision_score(y_true, y_scores) # doctest: +ELLIPSIS
0.79...
"""
precision, recall, thresholds = precision_recall_curve(y_true, y_score)
return auc(recall, precision)
def auc_score(y_true, y_score):
"""Compute Area Under the Curve (AUC) from prediction scores
Note: this implementation is restricted to the binary classification task.
Parameters
----------
y_true : array, shape = [n_samples]
True binary labels.
y_score : array, shape = [n_samples]
Target scores, can either be probability estimates of the positive
class, confidence values, or binary decisions.
Returns
-------
auc : float
References
----------
.. [1] `Wikipedia entry for the Receiver operating characteristic
<http://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_
See also
--------
average_precision_score : Area under the precision-recall curve
roc_curve : Compute Receiver operating characteristic (ROC)
Examples
--------
>>> import numpy as np
>>> from sklearn.metrics import auc_score
>>> y_true = np.array([0, 0, 1, 1])
>>> y_scores = np.array([0.1, 0.4, 0.35, 0.8])
>>> auc_score(y_true, y_scores)
0.75
"""
if len(np.unique(y_true)) != 2:
raise ValueError("AUC is defined for binary classification only")
fpr, tpr, tresholds = roc_curve(y_true, y_score)
return auc(fpr, tpr, reorder=True)
def matthews_corrcoef(y_true, y_pred):
"""Compute the Matthews correlation coefficient (MCC) for binary classes
The Matthews correlation coefficient is used in machine learning as a
measure of the quality of binary (two-class) classifications. It takes into
account true and false positives and negatives and is generally regarded as
a balanced measure which can be used even if the classes are of very
different sizes. The MCC is in essence a correlation coefficient value
between -1 and +1. A coefficient of +1 represents a perfect prediction, 0
an average random prediction and -1 an inverse prediction. The statistic
is also known as the phi coefficient. [source: Wikipedia]
Only in the binary case does this relate to information about true and
false positives and negatives. See references below.
Parameters
----------
y_true : array, shape = [n_samples]
Ground truth (correct) target values.
y_pred : array, shape = [n_samples]
Estimated targets as returned by a classifier.
Returns
-------
mcc : float
The Matthews correlation coefficient (+1 represents a perfect
prediction, 0 an average random prediction and -1 and inverse
prediction).
References
----------
.. [1] `Baldi, Brunak, Chauvin, Andersen and Nielsen, (2000). Assessing the
accuracy of prediction algorithms for classification: an overview
<http://dx.doi.org/10.1093/bioinformatics/16.5.412>`_
.. [2] `Wikipedia entry for the Matthews Correlation Coefficient
<http://en.wikipedia.org/wiki/Matthews_correlation_coefficient>`_
Examples
--------
>>> from sklearn.metrics import matthews_corrcoef
>>> y_true = [+1, +1, +1, -1]
>>> y_pred = [+1, -1, +1, +1]
>>> matthews_corrcoef(y_true, y_pred) # doctest: +ELLIPSIS
-0.33...
"""
y_true, y_pred = check_arrays(y_true, y_pred)
y_true, y_pred = _check_1d_array(y_true, y_pred, ravel=True)
mcc = np.corrcoef(y_true, y_pred)[0, 1]
if np.isnan(mcc):
return 0.
else:
return mcc
def precision_recall_curve(y_true, probas_pred):
"""Compute precision-recall pairs for different probability thresholds
Note: this implementation is restricted to the binary classification task.
The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
true positives and ``fp`` the number of false positives. The precision is
intuitively the ability of the classifier not to label as positive a sample
that is negative.
The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
true positives and ``fn`` the number of false negatives. The recall is
intuitively the ability of the classifier to find all the positive samples.
The last precision and recall values are 1. and 0. respectively and do not
have a corresponding threshold. This ensures that the graph starts on the
x axis.
Parameters
----------
y_true : array, shape = [n_samples]
True targets of binary classification in range {-1, 1} or {0, 1}.
probas_pred : array, shape = [n_samples]
Estimated probabilities or decision function.
Returns
-------
precision : array, shape = [n + 1]
Precision values.
recall : array, shape = [n + 1]
Recall values.
thresholds : array, shape = [n]
Thresholds on y_score used to compute precision and recall.
Examples
--------
>>> import numpy as np
>>> from sklearn.metrics import precision_recall_curve
>>> y_true = np.array([0, 0, 1, 1])
>>> y_scores = np.array([0.1, 0.4, 0.35, 0.8])
>>> precision, recall, threshold = precision_recall_curve(y_true, y_scores)
>>> precision # doctest: +ELLIPSIS
array([ 0.66..., 0.5 , 1. , 1. ])
>>> recall
array([ 1. , 0.5, 0.5, 0. ])
>>> threshold
array([ 0.35, 0.4 , 0.8 ])
"""
y_true = np.ravel(y_true)
probas_pred = np.ravel(probas_pred)
# Make sure input is boolean
labels = np.unique(y_true)
if np.all(labels == np.array([-1, 1])):
# convert {-1, 1} to boolean {0, 1} repr
y_true = y_true.copy()
y_true[y_true == -1] = 0
elif not np.all(labels == np.array([0, 1])):
raise ValueError("y_true contains non binary labels: %r" % labels)
# Sort pred_probas (and corresponding true labels) by pred_proba value
decreasing_probas_indices = np.argsort(probas_pred, kind="mergesort")[::-1]
probas_pred = probas_pred[decreasing_probas_indices]
y_true = y_true[decreasing_probas_indices]
# probas_pred typically has many tied values. Here we extract
# the indices associated with the distinct values. We also
# concatenate values for the beginning and end of the curve.
distinct_value_indices = np.where(np.diff(probas_pred))[0] + 1
threshold_idxs = np.hstack([0,
distinct_value_indices,
len(probas_pred)])
# Initialize true and false positive counts, precision and recall
total_positive = float(y_true.sum())
tp_count, fp_count = 0., 0. # Must remain floats to prevent int division
precision = [1.]
recall = [0.]
thresholds = []
# Iterate over indices which indicate distinct values (thresholds) of
# probas_pred. Each of these threshold values will be represented in the
# curve with a coordinate in precision-recall space. To calculate the
# precision and recall associated with each point, we use these indices to
# select all labels associated with the predictions. By incrementally
# keeping track of the number of positive and negative labels seen so far,
# we can calculate precision and recall.
for l_idx, r_idx in zip(threshold_idxs[:-1], threshold_idxs[1:]):
threshold_labels = y_true[l_idx:r_idx]
n_at_threshold = r_idx - l_idx
n_pos_at_threshold = threshold_labels.sum()
n_neg_at_threshold = n_at_threshold - n_pos_at_threshold
tp_count += n_pos_at_threshold
fp_count += n_neg_at_threshold
fn_count = total_positive - tp_count
precision.append(tp_count / (tp_count + fp_count))
recall.append(tp_count / (tp_count + fn_count))
thresholds.append(probas_pred[l_idx])
if tp_count == total_positive:
break
# sklearn expects these in reverse order
thresholds = np.array(thresholds)[::-1]
precision = np.array(precision)[::-1]
recall = np.array(recall)[::-1]
return precision, recall, thresholds
def roc_curve(y_true, y_score, pos_label=None):
"""Compute Receiver operating characteristic (ROC)
Note: this implementation is restricted to the binary classification task.
Parameters
----------
y_true : array, shape = [n_samples]
True binary labels in range {0, 1} or {-1, 1}. If labels are not
binary, pos_label should be explicitly given.
y_score : array, shape = [n_samples]
Target scores, can either be probability estimates of the positive
class, confidence values, or binary decisions.
pos_label : int
Label considered as positive and others are considered negative.
Returns
-------
fpr : array, shape = [>2]
False Positive Rates.
tpr : array, shape = [>2]
True Positive Rates.
thresholds : array, shape = [>2]
Thresholds on ``y_score`` used to compute ``fpr`` and ``fpr``.
See also
--------
auc_score : Compute Area Under the Curve (AUC) from prediction scores
Notes
-----
Since the thresholds are sorted from low to high values, they
are reversed upon returning them to ensure they correspond to both ``fpr``
and ``tpr``, which are sorted in reversed order during their calculation.
References
----------
.. [1] `Wikipedia entry for the Receiver operating characteristic
<http://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_
Examples
--------
>>> import numpy as np
>>> from sklearn import metrics
>>> y = np.array([1, 1, 2, 2])
>>> scores = np.array([0.1, 0.4, 0.35, 0.8])
>>> fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2)
>>> fpr
array([ 0. , 0.5, 0.5, 1. ])
"""
y_true = np.ravel(y_true)
y_score = np.ravel(y_score)
classes = np.unique(y_true)
# ROC only for binary classification if pos_label not given
if (pos_label is None and
not (np.all(classes == [0, 1]) or
np.all(classes == [-1, 1]) or
np.all(classes == [0]) or
np.all(classes == [-1]) or
np.all(classes == [1]))):
raise ValueError("ROC is defined for binary classification only or "
"pos_label should be explicitly given")
elif pos_label is None:
pos_label = 1.
# y_true will be transformed into a boolean vector
y_true = (y_true == pos_label)
n_pos = float(y_true.sum())
n_neg = y_true.shape[0] - n_pos
if n_pos == 0:
warnings.warn("No positive samples in y_true, "
"true positive value should be meaningless")
n_pos = np.nan
if n_neg == 0:
warnings.warn("No negative samples in y_true, "
"false positive value should be meaningless")
n_neg = np.nan
thresholds = np.unique(y_score)
neg_value, pos_value = False, True
tpr = np.empty(thresholds.size, dtype=np.float) # True positive rate
fpr = np.empty(thresholds.size, dtype=np.float) # False positive rate
# Build tpr/fpr vector
current_pos_count = current_neg_count = sum_pos = sum_neg = idx = 0
signal = np.c_[y_score, y_true]
sorted_signal = signal[signal[:, 0].argsort(), :][::-1]
last_score = sorted_signal[0][0]
for score, value in sorted_signal:
if score == last_score:
if value == pos_value:
current_pos_count += 1
else:
current_neg_count += 1
else:
tpr[idx] = (sum_pos + current_pos_count) / n_pos
fpr[idx] = (sum_neg + current_neg_count) / n_neg
sum_pos += current_pos_count
sum_neg += current_neg_count
current_pos_count = 1 if value == pos_value else 0
current_neg_count = 1 if value == neg_value else 0
idx += 1
last_score = score
else:
tpr[-1] = (sum_pos + current_pos_count) / n_pos
fpr[-1] = (sum_neg + current_neg_count) / n_neg
thresholds = thresholds[::-1]
if not (n_pos is np.nan or n_neg is np.nan):
# add (0,0) and (1, 1)
if not (fpr[0] == 0 and fpr[-1] == 1):
fpr = np.r_[0., fpr, 1.]
tpr = np.r_[0., tpr, 1.]
thresholds = np.r_[thresholds[0] + 1, thresholds,
thresholds[-1] - 1]
elif not fpr[0] == 0:
fpr = np.r_[0., fpr]
tpr = np.r_[0., tpr]
thresholds = np.r_[thresholds[0] + 1, thresholds]
elif not fpr[-1] == 1:
fpr = np.r_[fpr, 1.]
tpr = np.r_[tpr, 1.]
thresholds = np.r_[thresholds, thresholds[-1] - 1]
elif fpr.shape[0] == 2:
# trivial decisions, add (0,0)
fpr = np.array([0.0, fpr[0], fpr[1]])
tpr = np.array([0.0, tpr[0], tpr[1]])
# trivial decisions, add (0,0) and (1,1)
elif fpr.shape[0] == 1:
fpr = np.array([0.0, fpr[0], 1.0])
tpr = np.array([0.0, tpr[0], 1.0])
if n_pos is np.nan:
tpr[0] = np.nan
if n_neg is np.nan:
fpr[0] = np.nan
return fpr, tpr, thresholds
###############################################################################
# Multiclass general function
###############################################################################
def confusion_matrix(y_true, y_pred, labels=None):
"""Compute confusion matrix to evaluate the accuracy of a classification
By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}`
is equal to the number of observations known to be in group :math:`i` but
predicted to be in group :math:`j`.
Parameters
----------
y_true : array, shape = [n_samples]
Ground truth (correct) target values.
y_pred : array, shape = [n_samples]
Estimated targets as returned by a classifier.
labels : array, shape = [n_classes]
List of all labels occurring in the dataset.
If none is given, those that appear at least once
in ``y_true`` or ``y_pred`` are used.
Returns
-------
C : array, shape = [n_classes, n_classes]
Confusion matrix
References
----------
.. [1] `Wikipedia entry for the Confusion matrix
<http://en.wikipedia.org/wiki/Confusion_matrix>`_
Examples
--------
>>> from sklearn.metrics import confusion_matrix
>>> y_true = [2, 0, 2, 2, 0, 1]
>>> y_pred = [0, 0, 2, 2, 0, 2]
>>> confusion_matrix(y_true, y_pred)
array([[2, 0, 0],
[0, 0, 1],
[1, 0, 2]])
"""
if labels is None:
labels = unique_labels(y_true, y_pred)
else:
labels = np.asarray(labels)
n_labels = labels.size
label_to_ind = dict((y, x) for x, y in enumerate(labels))
# convert yt, yp into index
y_pred = np.array([label_to_ind.get(x, n_labels + 1) for x in y_pred])
y_true = np.array([label_to_ind.get(x, n_labels + 1) for x in y_true])
# intersect y_pred, y_true with labels, eliminate items not in labels
ind = np.logical_and(y_pred < n_labels, y_true < n_labels)
y_pred = y_pred[ind]
y_true = y_true[ind]
CM = np.asarray(
coo_matrix(
(np.ones(y_true.shape[0], dtype=np.int), (y_true, y_pred)),
shape=(n_labels, n_labels)
).todense()
)
return CM
###############################################################################
# Multiclass loss function
###############################################################################
def zero_one_loss(y_true, y_pred, normalize=True):
"""Zero-one classification loss.
If normalize is ``True``, return the fraction of misclassifications
(float), else it returns the number of misclassifications (int). The best
performance is 0.
Parameters
----------
y_true : array-like or list of labels or label indicator matrix
Ground truth (correct) labels.
y_pred : array-like or list of labels or label indicator matrix
Predicted labels, as returned by a classifier.
normalize : bool, optional (default=True)
If ``False``, return the number of misclassifications.
Otherwise, return the fraction of misclassifications.
Returns
-------
loss : float or int,
If ``normalize == True``, return the fraction of misclassifications
(float), else it returns the number of misclassifications (int).
Notes
-----
In multilabel classification, the zero_one_loss function corresponds to
the subset zero-one loss: for each sample, the entire set of labels must be
correctly predicted, otherwise the loss for that sample is equal to one.
See also
--------
accuracy_score, hamming_loss, jaccard_similarity_score
Examples
--------
>>> from sklearn.metrics import zero_one_loss
>>> y_pred = [1, 2, 3, 4]
>>> y_true = [2, 2, 3, 4]
>>> zero_one_loss(y_true, y_pred)
0.25
>>> zero_one_loss(y_true, y_pred, normalize=False)
1
In the multilabel case with binary indicator format:
>>> zero_one_loss(np.array([[0.0, 1.0], [1.0, 1.0]]), np.ones((2, 2)))
0.5
and with a list of labels format:
>>> zero_one_loss([(1,), (3,)], [(1, 2), tuple()])
1.0
"""
y_true, y_pred = check_arrays(y_true, y_pred, allow_lists=True)
score = accuracy_score(y_true, y_pred,
normalize=normalize)
if normalize:
return 1 - score
else:
if hasattr(y_true, "shape"):
n_samples = (np.max(y_true.shape) if _is_1d(y_true)
else y_true.shape[0])
else:
n_samples = len(y_true)
return n_samples - score
@deprecated("Function 'zero_one' has been renamed to "
"'zero_one_loss' and will be removed in release 0.15."
"Default behavior is changed from 'normalize=False' to "
"'normalize=True'")
def zero_one(y_true, y_pred, normalize=False):
"""Zero-One classification loss
If normalize is ``True``, return the fraction of misclassifications
(float), else it returns the number of misclassifications (int). The best
performance is 0.
Parameters
----------
y_true : array-like
y_pred : array-like
normalize : bool, optional (default=False)
If ``False`` (default), return the number of misclassifications.
Otherwise, return the fraction of misclassifications.
Returns
-------
loss : float
If normalize is True, return the fraction of misclassifications
(float), else it returns the number of misclassifications (int).
Examples
--------
>>> from sklearn.metrics import zero_one
>>> y_pred = [1, 2, 3, 4]
>>> y_true = [2, 2, 3, 4]
>>> zero_one(y_true, y_pred)
1
>>> zero_one(y_true, y_pred, normalize=True)
0.25
"""
return zero_one_loss(y_true, y_pred, normalize)
###############################################################################
# Multiclass score functions
###############################################################################
def jaccard_similarity_score(y_true, y_pred, normalize=True, pos_label=1):
"""Jaccard similarity coefficient score
The Jaccard index [1], or Jaccard similarity coefficient, defined as
the size of the intersection divided by the size of the union of two label
sets, is used to compare set of predicted labels for a sample to the
corresponding set of labels in ``y_true``.
Parameters
----------
y_true : array-like or list of labels or label indicator matrix
Ground truth (correct) labels.
y_pred : array-like or list of labels or label indicator matrix
Predicted labels, as returned by a classifier.
normalize : bool, optional (default=True)
If ``False``, return the sum of the Jaccard similarity coefficient
over the sample set. Otherwise, return the average of Jaccard
similarity coefficient.
pos_label : int, 1 by default
It is used to infer what is a positive label in the label indicator
matrix format.
Returns
-------
score : float
If ``normalize == True``, return the average Jaccard similarity
coefficient, else it returns the sum of the Jaccard similarity
coefficient over the sample set.
The best performance is 1 with ``normalize == True`` and the number
of samples with ``normalize == False``.
See also
--------
accuracy_score, hamming_loss, zero_one_loss
Notes
-----
In binary and multiclass classification, this function is equivalent
to the ``accuracy_score``. It differs in the multilabel classification
problem.
References
----------
.. [1] `Wikipedia entry for the Jaccard index
<http://en.wikipedia.org/wiki/Jaccard_index>`_
Examples
--------
>>> import numpy as np
>>> from sklearn.metrics import jaccard_similarity_score
>>> y_pred = [0, 2, 1, 3]
>>> y_true = [0, 1, 2, 3]
>>> jaccard_similarity_score(y_true, y_pred)
0.5
>>> jaccard_similarity_score(y_true, y_pred, normalize=False)
2
In the multilabel case with binary indicator format:
>>> jaccard_similarity_score(np.array([[0.0, 1.0], [1.0, 1.0]]),\
np.ones((2, 2)))
0.75
and with a list of labels format:
>>> jaccard_similarity_score([(1,), (3,)], [(1, 2), tuple()])
0.25
"""
y_true, y_pred = check_arrays(y_true, y_pred, allow_lists=True)
# Compute accuracy for each possible representation
if is_multilabel(y_true):
# Handle mix representation
if type(y_true) != type(y_pred):
labels = unique_labels(y_true, y_pred)
lb = LabelBinarizer()
lb.fit([labels.tolist()])
y_true = lb.transform(y_true)
y_pred = lb.transform(y_pred)
if is_label_indicator_matrix(y_true):
try:
# oddly, we may get an "invalid" rather than a "divide"
# error here
old_err_settings = np.seterr(divide='ignore',
invalid='ignore')
y_pred_pos_label = y_pred == pos_label
y_true_pos_label = y_true == pos_label
score = (np.sum(np.logical_and(y_pred_pos_label,
y_true_pos_label),
axis=1) /
np.sum(np.logical_or(y_pred_pos_label,
y_true_pos_label),
axis=1))
# If there is no label, it results in a Nan instead, we set
# the jaccard to 1: lim_{x->0} x/x = 1
score[np.isnan(score)] = 1.0
finally:
np.seterr(**old_err_settings)
else:
score = np.empty(len(y_true))
for i, (true, pred) in enumerate(zip(y_pred, y_true)):
true_set = set(true)
pred_set = set(pred)
size_true_union_pred = len(true_set | pred_set)