计算loss的函数,下面以均方差为例:
# coding: utf-8
# @时间 : 2022/3/20 2:59 下午
# @作者 : 那美那美
import tensorflow as tf
import numpy as np
out = tf.random.uniform([4, 10]) # 模拟最后一层的输出
y = tf.range(4) # 模拟真实值y,4个分类
y = tf.one_hot(y, depth=10) # 将y值进行one_hot编码
loss = tf.keras.losses.mse(y, out) # 方差
loss = tf.reduce_mean(loss) # 均方差后的结果
print(out, y, loss, sep='\n***************\n')
运行结果:
tf.Tensor(
[[0.95495164 0.42851162 0.63940954 0.7457049 0.863574 0.4137305
0.19719076 0.6347679 0.3381462 0.21893883]
[0.9869051 0.64940274 0.92230356 0.02006686 0.9132643 0.97518027
0.7332783 0.60538805 0.16506422 0.9878422 ]
[0.7512604 0.5606184 0.90563107 0.24399471 0.5856639 0.8866366
0.13660061 0.19366539 0.7147602 0.05145013]
[0.61691034 0.43103004 0.8596388 0.3836639 0.9826486 0.07203913