def confusion_matrix(y_true, y_pred, labels=None, sample_weight=None):
 (y_type, y_true, y_pred) = _check_targets(y_true, y_pred)
 if (y_type not in ('binary', 'multiclass')):
  raise ValueError(('%s is not supported' % y_type))
 if (labels is None):
  labels = unique_labels(y_true, y_pred)
 else:
  labels = np.asarray(labels)
  if np.all([(l not in y_true) for l in labels]):
   raise ValueError('At least one label specified must be in y_true')
 if (sample_weight is None):
  sample_weight = np.ones(y_true.shape[0], dtype=np.int)
 else:
  sample_weight = np.asarray(sample_weight)
 check_consistent_length(sample_weight, y_true, y_pred)
 n_labels = labels.size
 label_to_ind = dict(((y, x) for (x, y) in enumerate(labels)))
 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])
 ind = np.logical_and((y_pred < n_labels), (y_true < n_labels))
 y_pred = y_pred[ind]
 y_true = y_true[ind]
 sample_weight = sample_weight[ind]
 CM = coo_matrix((sample_weight, (y_true, y_pred)), shape=(n_labels, n_labels)).toarray()
 return CM

def confusion_matrix ( y_true , y_pred , labels = None , sample_weight = None ) : ( y_type , y_true , y_pred ) = _check_targets ( y_true , y_pred ) if ( y_type not in ( 'binary' , 'multiclass' ) ) : raise ValueError ( ( '%s is not supported' % y_type ) ) if ( labels is None ) : labels = unique_labels ( y_true , y_pred ) else : labels = np . asarray ( labels ) if np . all ( [ ( l not in y_true ) for l in labels ] ) : raise ValueError ( 'At least one label specified must be in y_true' ) if ( sample_weight is None ) : sample_weight = np . ones ( y_true . shape [ 0 ] , dtype = np . int ) else : sample_weight = np . asarray ( sample_weight ) check_consistent_length ( sample_weight , y_true , y_pred ) n_labels = labels . size label_to_ind = dict ( ( ( y , x ) for ( x , y ) in enumerate ( labels ) ) ) 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 ] ) ind = np . logical_and ( ( y_pred < n_labels ) , ( y_true < n_labels ) ) y_pred = y_pred [ ind ] y_true = y_true [ ind ] sample_weight = sample_weight [ ind ] CM = coo_matrix ( ( sample_weight , ( y_true , y_pred ) ) , shape = ( n_labels , n_labels ) ) . toarray ( ) return CM
compute confusion matrix args: res : evaluation results index : model index returns: confusion matrix .