这是另一种方式,使用bincount
:
from __future__ import division
import numpy as np
def confusionmatrix( true, predicted, classnames="0 1", verbose=1 ):
""" true aka y, observed class ids: ints [0 .. nclass) or bools
predicted aka yhat: ints or bools, e.g. (probs > threshold)
-> e.g.
confusion matrix, true down, predicted across:
[[0 2] -- true 0, pred 0 1
[7 1] -- true 1, pred 0 1
"""
true = np.asarray( true, dtype=int )
pred = np.asarray( predicted, dtype=int )
ntrue, npred = true.max() + 1, pred.max() + 1
counts = np.bincount( npred * true + pred, minlength = ntrue * npred ) # 00 01 10 11
confus = counts.reshape(( ntrue, npred ))
if verbose:
print "true counts %s: %s" % (classnames, np.bincount(true))
print "predicted counts %s: %s" % (classnames, np.bincount(pred))
print "confusion matrix, true down, predicted across:\n", confus
return confus
#...............................................................................
if __name__ == "__main__":
n = 10
np.random.seed( 7 )
y = np.random.randint( 0, 2, n )
p = np.random.randint( 0, 2, n )
print "true:", y
print "pred:", p
confusionmatrix( y, p )