TensorFlow2.0:梯度计算

本文介绍了在TensorFlow2.0中如何进行2阶梯度计算,详细讲解了sigmoid、tanh和relu等激活函数的使用,并探讨了MSE均方误差和交叉熵损失函数及其梯度的计算方法。
摘要由CSDN通过智能技术生成

**

一 2阶梯度的计算

**
将需要计算梯度的变量设置为tf.Variable( ),并将计算函数置于with tf.GradientTape ( ) as tape内.

import  tensorflow as tf

x = tf.Variable(tf.constant([2.]))
w = tf.Variable(tf.constant([2.]))
b = tf.Variable(tf.constant([2.]))

with tf.GradientTape(persistent=True) as tape1:
    with tf.GradientTape(persistent=True) as tape2:
        y = 3*x*w**3 + 2*x*w**2 + w*x + b**2
    dw,db = tape2.gradient(y,[w,b])
dw2 = tape1.gradient(dw,w)
db2 = tape1.gradient(db,b)

print(dw)
print(dw2)
print(db)
print(db2)

其输出结果为:

tf.Tensor([90.], shape=(1,), dtype=float32)
tf.Tensor([80.], shape=(1,), dtype=float32)
tf.Tensor([4.], shape=(1,), dtype=float32)
tf.Tensor([2.], shape=(1,), dtype=float32)

**

二 激活函数及梯度

**
2.1 sigmoid函数–tf.sigmoid( )
在这里插入图片描述
在这里插入图片描述

import tensorflow as tf

a = tf.Variable(tf.linspace(-10.,10.,10))

with tf.GradientTape( ) as tape:
    y = 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值