Sunday 11 April 2021

How to convert indices to one hot encoding, or vice versa?

from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

def indices_to_one_hot(data, nb_classes):
    """Convert an iterable of indices to one-hot encoded labels."""
    targets = np.array(data).reshape(-1)
    return np.eye(nb_classes)[targets]

def one_hot_to_indices(data):
    return np.argmax(data, axis=1)

 

#########################################

pred = one_hot_to_indices(one_hot_pred)
targ = one_hot_to_indices(one_hot_label)
prec1 = accuracy_score(pred, targ) # [0,1,1,0], [0,0,1,0]

cf = confusion_matrix(video_labels, video_pred).astype(float)
cr = classification_report(video_labels, video_pred)
print('confusion_matrix')
print(cf)
print('classification_report')
print(cr)

np.save('cm.npy', cf)
cls_cnt = cf.sum(axis=1)
cls_hit = np.diag(cf)

cls_acc = cls_hit / cls_cnt
print(cls_acc)
upper = np.mean(np.max(cf, axis=1) / cls_cnt)
print('upper bound: {}'.format(upper))

print('-----Evaluation is finished------')
print('Class Accuracy {:.02f}%'.format(np.mean(cls_acc) * 100))
print('Overall Prec@1 {:.02f}%'.format(top1.avg))



 



No comments:

Post a Comment