import numpy as np
def one_hot(labels):
'''one-hot编码'''
n_samples = len(labels)
n_class = max(labels)+1
onehot_labels = np.zeros((n_samples, n_class))
onehot_labels[np.arange(n_samples), labels] = 1
return onehot_labels
def to_categorial(labels):
n_samples = len(labels)
n_class = max(labels)+1
to_categorial_labels = np.zeros((n_samples, n_class))
for i in range(n_samples):
to_categorial_labels[i,labels[i]] = 1.0
return to_categorial_labels
label = np.array([0, 1, 2, 3, 4, 5])
print(one_hot(label))
print(to_categorial(label))
[[1. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 1.]]
[[1. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 1.]]