Tensorflow2.0笔记 - 均方差MSE和交叉熵CROSS ENTROPHY作为损失函数

        本笔记主要记录使用MSE和交叉熵作为loss function时的梯度计算方法。

import tensorflow as tf
import numpy as np

tf.__version__


#softmax函数使用
#参考资料:https://blog.csdn.net/u013230189/article/details/82835717
#简单例子:
#假设输出的LOGITS SCORE为:
#2.0
#1.0
#0.1
#使用softmax后,可以按照score得分高低来转换成概率大小,所有输出值相加为1:
#2.0     0.7
#1.0  -> 0.2
#0.1     0.1

#MSE均方差loss函数及其梯度计算
#参考资料:https://zhuanlan.zhihu.com/p/35707643
#下面例子中:x表示两个样本数据,每个数据是一个长度为4的tensor:[2,4]
x = tf.random.normal([2,4])
#输入数据的维度是4,输出节点我们定义为3维,表示3分类结果
w = tf.random.normal([4,3])
#bias初始化为0
b = tf.zeros([3])
#输出的label值,表示两个样本的真实label的class是2和0
y = tf.constant([2,0])

with tf.GradientTape() as tape:
    tape.watch([w,b])
    #使用softmax计算概率
    prob = tf.nn.softmax(x@w +b, axis=1)
    #使用MSE计算loss
    loss = tf.reduce_mean(tf.losses.MSE(tf.one_hot(y, depth=3), prob))
#求解损失函数的梯度
grads = tape.gradient(loss, [w,b])
print("Gradients of w:\n", grads[0].numpy())
print("Gradients of b:\n", grads[1].numpy())

#交叉熵loss函数及其梯度计算
#参考资料:https://zhuanlan.zhihu.com/p/38241764
#下面例子中:x表示两个样本数据,每个数据是一个长度为4的tensor:[2,4]
x = tf.random.normal([2,4])
#输入数据的维度是4,输出节点我们定义为3维,表示3分类结果
w = tf.random.normal([4,3])
#bias初始化为0
b = tf.zeros([3])
#输出的label值,表示两个样本的真实label的class是2和0
y = tf.constant([2,0])

with tf.GradientTape() as tape:
    tape.watch([w,b])
    #计算logits
    logits = x@w + b
    #使用交叉熵计算loss
    loss = tf.reduce_mean(tf.losses.categorical_crossentropy(tf.one_hot(y, depth=3), logits, from_logits=True))

#求解损失函数的梯度
grads = tape.gradient(loss, [w, b])
print("Gradients of w:\n", grads[0].numpy())
print("Gradients of b:\n", grads[1].numpy())

运行结果:

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-15 12:52:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-15 12:52:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-15 12:52:02       82 阅读
  4. Python语言-面向对象

    2024-03-15 12:52:02       91 阅读

热门阅读

  1. Docker使用及部署流程

    2024-03-15 12:52:02       37 阅读
  2. C++for语句

    2024-03-15 12:52:02       42 阅读
  3. 探索Python人工智能编程之道:从入门到实战

    2024-03-15 12:52:02       39 阅读
  4. docker日志在哪看?怎么在Linux服务器中查看日志

    2024-03-15 12:52:02       48 阅读
  5. Springboot参数分组校验

    2024-03-15 12:52:02       36 阅读
  6. 阿里云服务 安装 Docker

    2024-03-15 12:52:02       43 阅读