开发者学堂课程【Tensorflow2.0入门与实战:独热编码和交叉熵损失函数】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/664/detail/11107
独热编码和交叉熵损失函数
基本介绍
一.什么是独热编码
二.使用独热编码训练要注意的事项
一. 什么是独热编码
train_lable 是顺序编码,用0、1、2、3、4、5、6、7、8、9分别代表衬衫、鞋子等等将它编码成独热编码。
独热编码是一种数值化的方法。比如有三个城市分别是北京、上海、深圳,对这三个城市进行编码,可以编码成0、1、2,也可以编码成与它长度相同的维度。北京编码为【1,0,0】,上海【0,1,0】,深圳【0,0,1】标志为这个城市的为1其它地方都为0。
当 label 进行独热编码时使用 categorical_ crossentropy 交叉熵。将 train_lable 进行独热编码改成 train_label_onehot,onehot 代表独热编码,tf.keras.utils.to_categorical 将顺序编码变为独热编码。
train_label_onehot=tf.keras.utils.to_categorical(train_lable)
train label_onehot
array([[0.,0.,0.,..., 0.,0.,1.],
[1.,0.,0.,..., 0.,0.,0.],
[1.,0.,0.,..., 0.,0.,0.],
...,
[0.,0.,0.,..., 0.,0.,0.],
[1.,0.,0.,..., 0.,0.,0.],
[0.,0.,0.,..., 0.,0.,0.]],dtype=float32)
9将会变化成[0.,0.,0.,..., 0.,0.,1.],长度为十的向量,最后一位被标注为1
train_label_onehot[0]
array([0.,0.,0.,0.,0.,0.,0.,0.,0.,1.],dtype=float32)
最后一个5变化成独热编码[0.,0.,0.,0.,0.,1.,0.,0.,0.,0.]
train_label_onehot[-1]
array([0.,0.,0.,0.,0.,1.,0.,0.,0.,0.],dtype=float32)
可以将 test 数据集做成独热编码,
同样使用tf.keras.utils.to_categorical
test_label_onehot =tf.keras.utils.to_categorical(test_label)
test_label_onehot
array([[0.,0.,0.,..., 0.,0.,1.].
[0.,0.,1.,..., 0.,0.,0.],
[0.,1.,0.,..., 0.,0.,0.],
...,
[0.,0.,0.,..., 0.,1.,0.],
[0.,1.,0.,..., 0.,0.,0.],
[0.,0.,0.,..., 0.,0.,0.]],dtype=float32)
分类数据进行处理时也会讲到独热编码,可以算为一种方法。
test_label 第一个为9变化为[0.,0.,0.,..., 0.,0.,1.],第二个2变化为[0.,0.,1.,..., 0.,0.,0.]
二.使用独热编码训练要注意的事项
建立与之前相同的网络,复制网络。训练5个 epochs
model =tf.keras. Sequential()
model.add(tf.keraslayers.Flatten(input_shape=(28,28)))#28*28
model.add(tf.keras.layers.Dense(128,activation='relu')) model.add(tf.keras.lavers.Dense(10.activation=softmax)
model.compile(optimizer=adam',
loss='categorical_crossentropy’,
metrics=['acc']
)
model. fit(train_image, train_lable,epochs=5)
注意:
当 label 是顺序编码时使用的交叉熵损失函数是 sparse_categorical_crossentropy,label 是独热编码时使用 categorical_crossentropy,loss 值独热编码使用 categorical_crossentropy。数据使用的是 train 数据,但是编码使用的是 categorical_crossentropy 所以会报错。应该使用 train_label_onehot
model. fit(train_image,train_label_onehot,epochs=5
对 test_image 进行 predict,查看 predict 的形状,有10000个长度为10的向量
predict=model.predict(test_image)
predict.shape
(10000, 10)
test 数据集的形状,10000张图片
test_image.shape
(10000,28,28)
第一个分类结果
predict[0]
array([7.7417062e-05,1.2555851e-07,5.2015298e-06,3.90
63170e-06,6.1778355e-06,1.3308496e-02,5.2028918e-05,1,2039219e-02,6.5957895e-05,9.7444147e-01]dtype=float32)
softmax 的输出所有分量样本之和为1,所有样本相加的可能性为100%。哪个最大就是要预测的值。
使用 np.argamx 取出最大值所在的缩影
np.argamx(predict[0])
9
test_label[0]
9
说明预测的结果是正确的。