onehot编码在深度学习领域有着举足轻重的作用。无论是分类问题(classification)还是序列模型中对输入量的编码,都有它的身影。下面就用几种方法实现onehot encoding。
先定义一个y向量
y = np.array([3, 2, 4, 1, 5, 0]) # 定义一个y向量
最简朴的办法
one_hot_1 = np.zeros((max(y)+1, y.shape[0])) # onehot encoder
for i in range(y.shape[0]):
one_hot_1[y[i]][i] = 1
print(one_hot_1)
程序的运行结果如下:
其中矩阵的每一列代表一个训练样本对y的编码结果,下面实验的结果相同。
利用np.eye(K)[array]
one_hot_2 = np.eye(y.shape[0])[y.reshape(-1)].T
print(one_hot_2)
每次抓一行
I = np.eye(max(y)+1)
one_hot_3 = np.zeros((y.shape[0], max(y)+1))
for i in range(y.shape[0]):
one_hot_3[i] = I[y[i]]
one_hot_3 = one_hot_3.T
print(one_hot_3)
TensorFlow中内置的one_hot encoder
indices = [0,2,3,5]
depth1 = 6 # indices没有元素超过(depth-1)
depth2 = 4 # indices有元素超过(depth-1)
a = tf.one_hot(indices,depth1)
b = tf.one_hot(indices,depth2)
with tf.Session() as sess:
print('a = \n',sess.run(a))
print('b = \n',sess.run(b))
随着输入量的空间不断变大,onehot这种稀疏的编码方式逐渐变得十分鸡肋,因此诞生了词向量方式(WordEmbedding)来克服稀疏存储上的表示问题。