Tensorflow学习笔记(六)均方误差损失函数,MSE

一、均方误差损失函数

对于回归问题,最常用的损失函数就是均方误差损失函数(MSE)
定义如下:
在这里插入图片描述
其中yi为输出中第i个数据的答案值,yi‘ 就是神经网络给出的预测值。因此最小化该函数就是优化的目标。
通过最小二乘法,可以获得让MSE最小的数值。令偏导分别为0,则会有一个方程组,方程组化简后,会得到一个由n,yi,xi表达的式子,这样就可以获得相应的方程组,方便计算机求解。
最终会转化成下图的形式:
在这里插入图片描述
在这里插入图片描述

二、自定义损失函数

举例说明自定义损失函数:
若预测某商品的出货量,每比实际的多出1个则损失2元,每比实际的少1个则损失5元。
因此它的损失函数可以如下表达:
在这里插入图片描述
最小化上述的损失函数,则可以给出最佳的出货量。
在tensorflow中可以通过
where()和greater()函数实现上述的损失函数。

loss  =tf.reduce_sun(tf.where(tf.greater(y,y_),(y-y_)*a,(y_-y)*b))
#greater()输入两个张量(同维度),此函数会比较两个张量对应位置的大小,第一个大于第二个则返回True
#where()为选择功能,第一个为选择条件。是一个bool张量,当为True时会选择第二个进行执行,否则执行第三个

例程如下:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()
a = tf.constant([1.0,2.0,3.0,4.0,])
b = tf.constant([6.0,5.0,4.0,3.0,])
with tf.compat.v1.Session() as sess:
    print(tf.greater(a,b))
    print(tf.where(tf.greater(a,b),a,b))
    print(sess.run(tf.greater(a,b)))
    print(sess.run(tf.where(tf.greater(a,b),a,b)))

输出结果:
......
......
......
Skipping registering GPU devices...
2020-06-30 15:56:49.766413: I tensorflow/core/platform/cpu_feature_guard.cc:143] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2020-06-30 15:56:49.778833: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x22aeb00e460 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-06-30 15:56:49.779383: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
2020-06-30 15:56:49.779798: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1102] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-06-30 15:56:49.780145: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1108]      
Tensor("Greater:0", shape=(4,), dtype=bool)
Tensor("SelectV2:0", shape=(4,), dtype=float32)
[False False False  True]
[6. 5. 4. 4.]
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值