[深度之眼]TensorFlow2.0项目班-原理之损失函数(CE,MSE)

TF2.0损失函数大全
分类问题常使用交叉熵损失函数(CE,Cross Entropy)表征两个概率分布之间的距离
定义为:
在这里插入图片描述
例如一个二分类问题的答案是 y_=(1,0),预测 y1=(0.6,0.4) ,y2=(0.8,0.2),哪个预测的更准的?

数学计算
CE1 = CE((1,0),(0.6,0.4) = -(1*ln0.6 + 0*ln0.4) = 0.511
CE2 = CE((1,0),(0.8,0.2) = -(1*ln0.8 + 0*ln0.2) = 0.223

因为CE2<CE1,所以 y2 预测更准
利用 tf.losses.categorical_cossentropy() 函数进行验证

loss_ce1 = tf.losses.categorical_crossentropy([1, 0], [0.6, 0.4])
loss_ce2 = tf.losses.categorical_crossentropy([1, 0], [0.8, 0.2])

print输出:
loss_ce1: tf.Tensor(0.5108256, shape=(), dtype=float32)
loss_ce2: tf.Tensor(0.22314353, shape=(), dtype=float32)

回归问题常使用均方根误差损失函数(MSE,Mean Squared Error)
定义为:
在这里插入图片描述
例如一个回归问题的答案是 [1,2,3,4],预测 y1=[1,2,4,8] ,y2=[2,4,6,8]

数学计算
MSE1 = (0+0+1+4)/4 = 4.25
MSE2 = (1+4+9+16)/4 = 7.5

利用 tf.reduce_mean(tf.square()) 函数进行验证

y_ = tf.constant([1,2,3,4],dtype=tf.float32)
y1 = tf.constant([1,2,4,8],dtype=tf.float32)
y2 = tf.constant([2,4,6,8],dtype=tf.float32)
loss_mse1 = tf.reduce_mean(tf.square(y_-y1))
loss_mse2 = tf.reduce_mean(tf.square(y_-y2))

print输出:
loss_mse1: tf.Tensor(4.25, shape=(), dtype=float32)
loss_mse2: tf.Tensor(7.5, shape=(), dtype=float32)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章