Skip to content

Commit

Permalink
fixed issue scikit-learn#3450 for hamming loss
Browse files Browse the repository at this point in the history
  • Loading branch information
achab committed Oct 19, 2015
1 parent 6db9ee0 commit bf8f3f1
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions sklearn/metrics/classification.py
Expand Up @@ -202,6 +202,7 @@ def confusion_matrix(y_true, y_pred, labels=None):
If none is given, those that appear at least once
in ``y_true`` or ``y_pred`` are used in sorted order.
Returns
-------
C : array, shape = [n_classes, n_classes]
Expand Down Expand Up @@ -1392,7 +1393,7 @@ class 2 1.00 0.67 0.80 3
return report


def hamming_loss(y_true, y_pred, classes=None):
def hamming_loss(y_true, y_pred, classes=None, sample_weight=None):
"""Compute the average Hamming loss.
The Hamming loss is the fraction of labels that are incorrectly predicted.
Expand All @@ -1410,6 +1411,9 @@ def hamming_loss(y_true, y_pred, classes=None):
classes : array, shape = [n_labels], optional
Integer array of labels.
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
Returns
-------
loss : float or int,
Expand Down Expand Up @@ -1457,6 +1461,7 @@ def hamming_loss(y_true, y_pred, classes=None):
>>> hamming_loss(np.array([[0, 1], [1, 1]]), np.zeros((2, 2)))
0.75
"""
check_consistent_length(y_true, y_pred, sample_weight)
y_type, y_true, y_pred = _check_targets(y_true, y_pred)

if classes is None:
Expand All @@ -1465,11 +1470,11 @@ def hamming_loss(y_true, y_pred, classes=None):
classes = np.asarray(classes)

if y_type.startswith('multilabel'):
n_differences = count_nonzero(y_true - y_pred)
n_differences = count_nonzero(y_true - y_pred, sample_weight)
return (n_differences / (y_true.shape[0] * len(classes)))

elif y_type in ["binary", "multiclass"]:
return sp_hamming(y_true, y_pred)
return _weighted_sum(y_true != y_pred, sample_weight, normalize=True)
else:
raise ValueError("{0} is not supported".format(y_type))

Expand Down

0 comments on commit bf8f3f1

Please sign in to comment.