tensorflow2.0学习笔记第二章第四节
2.4损失函数
损失函数(loss):预测值(y)与已知答案(y_)的差距
nn优化目标:loss最小->-mse
-自定义
-ce(cross entropy)
均方误差mse:MSE(y_,y)=E^n~i=1(y-y_)^2/n
loss_mse = tf.reduce_mean(tf.square(y_-y))
import tensorflow as tf
import numpy as np SEED = 23455 rdm = np.random.RandomState(seed=SEED)
x = rdm.rand(32,2)
y_ = [[x1 + x2 + (rdm.rand()/10.0 - 0.05)] for (x1,x2) in x] # 生成【0,1】/10-0.05的噪声
x = tf.cast(x,dtype = tf.float32) w1 = tf.Variable(tf.random.normal([2,1],stddev=1, seed = 1)) # 创建一个2行一列的参数矩阵 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) # loss_mse对w1求导
w1.assign_sub(lr*grads) # 在原本w1上减去lr(学习率)*求导结果 if epoch % 500 == 0:
print('After %d training steps,w1 is'%(epoch))
print(w1.numpy(),"\n")
print("Final w1 is:",w1.numpy())
结果:
After 0 training steps,w1 is
[[-0.8096241]
[ 1.4855157]]
After 500 training steps,w1 is
[[-0.21934733]
[ 1.6984866 ]]
After 1000 training steps,w1 is
[[0.0893971]
[1.673225 ]]
After 1500 training steps,w1 is
[[0.28368822]
[1.5853055 ]]
........
........
After 14000 training steps,w1 is
[[0.9993659]
[0.999166 ]]
After 14500 training steps,w1 is
[[1.0002553 ]
[0.99838644]]
Final w1 is: [[1.0009792]
[0.9977485]]
自定义损失函数
如预测商品销量,预测多了,损失成本,预测少了损失利润
若利润!=成本,则mse产生的loss无法利益最大化
自定义损失函数 loss(y_-y)=Ef(y_-y) f(y_-y)={profit*(y_-y) ,y<y_ 预测少了,损失利润
{cost*(y_-y) ,y>y_ 预测多了,损失成本 写出函数:
loss_zdy = tf.reduce_sum(tf.where(tf.greater(y_,y),(profit*(y_-y),cost*(y-y_) ))) 假设商品成本1元,利润99元,则预测后的参数偏大,预测销量较高,反之成本为99利润为1则参数小,销售预测较小
import tensorflow as tf
import numpy as np profit = 1
cost = 99
SEED = 23455
rdm = np.random.RandomState(seed=SEED)
x = rdm.rand(32,2)
x = tf.cast(x,tf.float32)
y_ = [[x1+x2 + rdm.rand()/10.0-0.05] for x1,x2 in x]
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_zdy = tf.reduce_sum(tf.where(tf.greater(y_,y),(y_-y)*profit,(y-y_)*cost)) grads = tape.gradient(loss_zdy,w1)
w1.assign_sub(lr*grads) if epoch % 500 == 0:
print("after %d epoch w1 is:"%epoch)
print(w1.numpy(),'\n')
print('--------------')
print('final w1 is',w1.numpy()) # 当成本=1,利润=99模型的两个参数[[1.1231122][1.0713713]] 均大于1模型在往销量多的预测
# 当成本=99,利润=1模型的两个参数[[0.95219666][0.909771 ]] 均小于1模型在往销量少的预测
交叉熵损失函数CE(cross entropy),表示两个概率分布之间的距离
H(y_,y)= -Ey_*lny
如:二分类中标准答案y_=(1,0),预测y1=(0.6,0.4),y2=(0.8,0.2)
哪个更接近标准答案?
H1((1,0),(0.6,0.4))=-(1*ln0.6 + 0*ln0.4) =0.511
H2((1,0),(0.8,0.2))=0.223
因为h1>H2,所以y2预测更准
tf中交叉熵的计算公式:
tf.losses.categorical_crossentropy(y_,y)
import tensorflow as tf
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",loss_ce1)
print("loss_ce2",loss_ce2)
#loss_ce1 tf.Tensor(0.5108256, shape=(), dtype=float32)
#loss_ce2 tf.Tensor(0.22314353, shape=(), dtype=float32)
# 结果loss_ce2数值更小更接近
softmax与交叉熵结合
输出先过softmax,再计算y_和y的交叉损失函数
tf.nn.softmax_cross_entroy_with_logits(y_,y)
tensorflow2.0学习笔记第二章第四节的更多相关文章
- tensorflow2.0学习笔记第一章第四节
1.4神经网络实现鸢尾花分类 import tensorflow as tf from sklearn import datasets import pandas as pd import numpy ...
- tensorflow2.0学习笔记第二章第一节
2.1预备知识 # 条件判断tf.where(条件语句,真返回A,假返回B) import tensorflow as tf a = tf.constant([1,2,3,1,1]) b = tf.c ...
- tensorflow2.0学习笔记第二章第三节
2.3激活函数sigmoid函数 f(x)= 1/(1 + e^-x)tf.nn.sigmoid(x)特点:(1)求导后的数值在0-0.25之间,链式相乘之后容易使得值趋近于0,形成梯度消失 (2)输 ...
- tensorflow2.0学习笔记第二章第二节
2.2复杂度和学习率 指数衰减学习率可以先用较大的学习率,快速得到较优解,然后逐步减少学习率,使得模型在训练后期稳定指数衰减学习率 = 初始学习率 * 学习率衰减率^(当前轮数/多少轮衰减一次) 空间 ...
- tensorflow2.0学习笔记第一章第五节
1.5简单神经网络实现过程全览
- tensorflow2.0学习笔记第一章第二节
1.2常用函数 本节目标:掌握在建立和操作神经网络过程中常用的函数 # 常用函数 import tensorflow as tf import numpy as np # 强制Tensor的数据类型转 ...
- tensorflow2.0学习笔记第一章第一节
一.简单的神经网络实现过程 1.1张量的生成 # 创建一个张量 #tf.constant(张量内容,dtpye=数据类型(可选)) import tensorflow as tf import num ...
- tensorflow2.0学习笔记第一章第三节
1.3鸢尾花数据读入 # 从sklearn包datasets读入数据 from sklearn import datasets from pandas import DataFrame import ...
- 《DOM Scripting》学习笔记-——第二章 js语法
<Dom Scripting>学习笔记 第二章 Javascript语法 本章内容: 1.语句. 2.变量和数组. 3.运算符. 4.条件语句和循环语句. 5.函数和对象. 语句(stat ...
随机推荐
- PAT 1011 World Cup Betting (20分) 比较大小难度级别
题目 With the 2010 FIFA World Cup running, football fans the world over were becoming increasingly exc ...
- 搞懂:前端跨域问题JS解决跨域问题VUE代理解决跨域问题原理
什么是跨域 跨域:一个域下的文档或脚本试图去请求另一个域下的资源 广义的跨域包含一下内容: 1.资源跳转(链接跳转,重定向跳转,表单提交) 2.资源请求(内部的引用,脚本script,图片img,fr ...
- protus中出现invalid internal memory size ==NULL
点击8086芯片,更改internal memory size的大小为0x10000
- JS的函数和对象三
复习 判断是否含有某个属性 对象.属性名 === undefined 对象.hasOwnProperty('属性名') '属性名' in 对象 方法 { say:function(){ this ...
- 发现用System.Net.Mail发邮件(代码附后),附件稍微大一点就会造成程序假死. 有没有什么简单的解决办法呢? 多谢!!
附件大,上传,发送一定会慢.程序卡,应该是主线程正在发送,邮件造成的.创建其他线程在后台去发.这样就不影响主线程做其他工作了 using System; using System.Collecti ...
- Struts2导图
- poj3177 无向连通图加多少条边变成边双连通图
Redundant Paths Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 15752 Accepted: 6609 ...
- 玩转java反射
玩玩JAVA反射 什么是反射 Java反射机制是在运行状态中,对于任意一个类,都能知道这个类的所有属性和方法:对于任何一个对象,都能够调用它的任何一个方法和属性:这样动态获取新的以及动态调用对象的方法 ...
- Java——删除Map集合中key-value值
通过迭代器删除Map集合中的key-value值 Iterator<String> iter = map.keySet().iterator(); while(iter.hasNext() ...
- ngnix随笔四
1.alias path 例1. =>http://www.a.com/bbs/ root /data/vhosts/; location /bbs/{ alias /data/a.com/; ...