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学习笔记第二章第四节的更多相关文章

  1. tensorflow2.0学习笔记第一章第四节

    1.4神经网络实现鸢尾花分类 import tensorflow as tf from sklearn import datasets import pandas as pd import numpy ...

  2. tensorflow2.0学习笔记第二章第一节

    2.1预备知识 # 条件判断tf.where(条件语句,真返回A,假返回B) import tensorflow as tf a = tf.constant([1,2,3,1,1]) b = tf.c ...

  3. tensorflow2.0学习笔记第二章第三节

    2.3激活函数sigmoid函数 f(x)= 1/(1 + e^-x)tf.nn.sigmoid(x)特点:(1)求导后的数值在0-0.25之间,链式相乘之后容易使得值趋近于0,形成梯度消失 (2)输 ...

  4. tensorflow2.0学习笔记第二章第二节

    2.2复杂度和学习率 指数衰减学习率可以先用较大的学习率,快速得到较优解,然后逐步减少学习率,使得模型在训练后期稳定指数衰减学习率 = 初始学习率 * 学习率衰减率^(当前轮数/多少轮衰减一次) 空间 ...

  5. tensorflow2.0学习笔记第一章第五节

    1.5简单神经网络实现过程全览

  6. tensorflow2.0学习笔记第一章第二节

    1.2常用函数 本节目标:掌握在建立和操作神经网络过程中常用的函数 # 常用函数 import tensorflow as tf import numpy as np # 强制Tensor的数据类型转 ...

  7. tensorflow2.0学习笔记第一章第一节

    一.简单的神经网络实现过程 1.1张量的生成 # 创建一个张量 #tf.constant(张量内容,dtpye=数据类型(可选)) import tensorflow as tf import num ...

  8. tensorflow2.0学习笔记第一章第三节

    1.3鸢尾花数据读入 # 从sklearn包datasets读入数据 from sklearn import datasets from pandas import DataFrame import ...

  9. 《DOM Scripting》学习笔记-——第二章 js语法

    <Dom Scripting>学习笔记 第二章 Javascript语法 本章内容: 1.语句. 2.变量和数组. 3.运算符. 4.条件语句和循环语句. 5.函数和对象. 语句(stat ...

随机推荐

  1. PAT 1001 A+B Format (20分) to_string()

    题目 Calculate a+b and output the sum in standard format -- that is, the digits must be separated into ...

  2. ql自动化测试之路-概述篇

    前言:本节主要讲解自动化测试的基本概述,包括分层自动化测试.自动化测试中用到的工具.以及关于自动化测试的想法 一.分层自动化测试 上图是经典的测试金字塔.用它来形容目前测试投入的价值是比较适合的,同样 ...

  3. vue登录路由验证(转)

    转载自:https://blog.csdn.net/github_39088222/article/details/80749219 vue的项目的登录状态(如果用vuex状态管理,页面一刷新vuex ...

  4. POJ1321棋盘问题(DFS)

    Description 在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别.要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子 ...

  5. Codeforces1183C(C题)Computer Game

    Vova is playing a computer game. There are in total nn turns in the game and Vova really wants to pl ...

  6. 4.1Go if-else

    1. Go if-else Golang程序的流程控制决定程序如何执行,主要有三大流程控制,顺序控制.分支控制.循环控制. 条件语句需要定义一个或多个条件,并且对条件测试的true或false来决定是 ...

  7. jQuery下实现等待指定元素加载完毕(可改成纯js版)

    http://www.poluoluo.com/jzxy/201307/233374.html 代码如下: jQuery.fn.wait = function (func, times, interv ...

  8. Align Content Properties

    How to align the items of the flexible element? <!DOCTYPE html> <html lang="en"&g ...

  9. 实验三:Linux系统用户管理及VIM配置

    项目 内容 这个作业属于哪个课程 班级课程的主页链接 这个作业的要求在哪里 作业要求链接地址 学号-姓名 17043133-木腾飞 学习目标 1.学习Linux系统用户管理2.学习vim使用及配置 实 ...

  10. .Net Core之仓储(Repository)模式

    我们经常在项目中使用仓储(Repository)模式,来实现解耦数据访问层与业务层.那在.net core使用EF core又是怎么做的呢? 现在我分享一下我的实现方案: 一.在领域层创建Reposi ...