Tensorflow2.0学习笔记-损失函数

损失函数(loss)

损失函数是使预测值y与已知答案y_的差距,神经网络的优化目标是让loss最小,主流的损失函数有3中计算方法:均方误差mse(Mean Squared Error),自定义函数,交叉熵。下面使用商品销量的例子进行代码运行。

1.mse损失函数
loss_mse = tf.reduce_mean(tf.square(y_ - y))

例程代码:

SEED = 23455  # 确定随机种子,使得每一次的随机数相同
#  生成数据集
rdm = np.random.RandomState(seed=SEED)  # 生成[0,1)之间的随机数
x = rdm.rand(32, 2)
#  x1和x2为销量的因素,y_为销量
y_ = [[x1 + x2 + (rdm.rand() / 10.0 - 0.05)] for (x1, x2) in x]  # 生成噪声[0,1)/10=[0,0.1); [0,0.1)-0.05=[-0.05,0.05)
x = tf.cast(x, dtype=tf.float32)
#  设置神经网络权重
w1 = tf.Variable(tf.random.normal([2, 1], stddev=1, seed=1))

epoch = 15000  # 确定训练次数
lr = 0.002  # 定义学习率
#  开始训练
for epoch in range(epoch):
    with tf.GradientTape() as tape:
        y = tf.matmul(x, w1)
        loss_mse = tf.reduce_mean(tf.square(y_ - y))

    grads = tape.gradient(loss_mse, w1)
    w1.assign_sub(lr * grads)

# 每训练500次输出一次训练结果
    if epoch % 500 == 0:
        print("After %d training steps,w1 is " % (epoch))
        print(w1.numpy(), "\n")
print("Final w1 is: ", w1.numpy())
2.自定义损失函数

我们在实际训练中,需要自己写一些损失函数使训练值更符合要求。例子如下
定义的损失函数:

loss = tf.reduce_sum(tf.where(tf.greater(y, y_), (y - y_) * COST, (y_ - y) * PROFIT))

整体代码如下:

SEED = 23455
#  在进行训练时,可以将成本和利润进行互换,然后再查看训练出的结果
COST = 1  #99
PROFIT = 99 #1
#  生成数据集
rdm = np.random.RandomState(SEED)
x = rdm.rand(32, 2)
y_ = [[x1 + x2 + (rdm.rand() / 10.0 - 0.05)] for (x1, x2) in x]  # 生成噪声[0,1)/10=[0,0.1); [0,0.1)-0.05=[-0.05,0.05)
x = tf.cast(x, dtype=tf.float32)

w1 = tf.Variable(tf.random.normal([2, 1], stddev=1, seed=1))
#设置训练步数和学习率
epoch = 10000
lr = 0.002

for epoch in range(epoch):
    with tf.GradientTape() as tape:
        y = tf.matmul(x, w1)
        loss = tf.reduce_sum(tf.where(tf.greater(y, y_), (y - y_) * COST, (y_ - y) * PROFIT))

    grads = tape.gradient(loss, w1)
    w1.assign_sub(lr * grads)

    if epoch % 500 == 0:
        print("After %d training steps,w1 is " % (epoch))
        print(w1.numpy(), "\n")
print("Final w1 is: ", w1.numpy())

输出结果:对比两个不同的成本和利润,我们可以看到,在利润高的时候,会多预测一些,成本高的时候会少预测一些。

#  cost = 1,profit = 99
Final w1 is:  [[1.1626335]
 [1.1191947]]

#  cost = 99,proflt = 1
Final w1 is:  [[0.9205433]
 [0.9186459]]
交叉熵函数

交叉熵损失函数CE:表征两个概率分布之间的距离,计算公式如下
H(y_, y) = -Σy_ * lny

1. tf.losses.categorical_crossentropy()

在tensorflow中,可以使用tf.losses.categorical_crossentropy()函数进行计算
例:预测概率为y1=(0.6,0.4),y2 = (0.8,0.2)

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

输出结果

loss_ce1: tf.Tensor(0.5108256, shape=(), dtype=float32)
loss_ce2: tf.Tensor(0.22314353, shape=(), dtype=float32)
2. tf.nn.softmax_cross_entropy_with_logits()

在实际运算中,可以用softmax和交叉熵进行配合使用,将要运算的输入先进行概率分布,然后在进行运算。
示例代码如下:

y_ = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0]])
y = np.array([[12, 3, 2], [3, 10, 1], [1, 2, 5], [4, 6.5, 1.2], [3, 6, 1]])
#  分布计算
y_pro = tf.nn.softmax(y)
loss_ce1 = tf.losses.categorical_crossentropy(y_, y_pro)
print('分步计算的结果:\n', loss_ce1)

输出结果:

分步计算的结果:
 tf.Tensor(
[1.68795487e-04 1.03475622e-03 6.58839038e-02 2.58349207e+00
 5.49852354e-02], shape=(5,), dtype=float64)

在tensorflow中可以使用函数tf.nn.softmax_cross_entropy_with_logits()来代替上例中的分布计算,示例如下:

y_ = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0]])
y = np.array([[12, 3, 2], [3, 10, 1], [1, 2, 5], [4, 6.5, 1.2], [3, 6, 1]])
y_pro = tf.nn.softmax(y)
#  综合计算
loss_ce2 = tf.nn.softmax_cross_entropy_with_logits(y_, y)

输出结果:

 tf.Tensor(
[1.68795487e-04 1.03475622e-03 6.58839038e-02 2.58349207e+00
 5.49852354e-02], shape=(5,), dtype=float64)
 #  我们可以得到输出结果相同
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值