tf.GradientTape() 使用

摘要:
Importtensorflowstfw=tf。常数(1.)x=tf。常数(2.)y=x*wwithtf。GradientTape()astape:[w])打印(grad1)结果为[None],因为y=x*w未与tf一起放置。GradientTape()静态:
import  tensorflow as tf

w = tf.constant(1.)
x = tf.constant(2.)

y = x*w

with tf.GradientTape() as tape:
tape.watch([w])
y2 = x*w
grad1 = tape.gradient(y,[w])

print(grad1)


结果为[None]
因为 y= x* w 没有放在 with tf.GradientTape() as tape:中。所以无法计算.如果w 已经是tf.Variable类型,就不需要放在GradientType中了


import  tensorflow as tf

w = tf.constant(1.)
x = tf.constant(2.)

y = x*w

with tf.GradientTape() as tape:
tape.watch([w])
y2 = x*w
grad2 = tape.gradient(y2,[w])

print(grad2)
结果 为:[<tf.Tensor: id=6, shape=(), dtype=float32, numpy=2.0>].
注意 [w] 中的w必须放在tape.watch()中.因为这个w不是tf.Variable型。
import  tensorflow as tf

x = tf.random.normal([2,4])
w = tf.random.normal([4,3])

b = tf.zeros([3])
y = tf.constant([2,0])

with tf.GradientTape() as tape:
tape.watch([w,b])
logits = x@w + b
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(grads)


x =tf.random.normal([2,4])
w = tf.Variable(tf.random.normal([4,3]))

b = tf.Variable(tf.zeros([3]))
y = tf.constant([2,0])

with tf.GradientTape() as tape:
# tape.watch([w,b]) 注意 w,b 已经是 tf.Variable类型了。就不需要watch了。
    logits = x@w + b
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(grads)



第三点:Persistent 参数.为True才可以连续求梯度.否则会报错.
with tf.GradientTape( persistent = True) as tape:

第4点。二阶求导:DMEO.一般很少用到。
tf.GradientTape()  使用第1张
 


免责声明:文章转载自《tf.GradientTape() 使用》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Android的Window类 ——转Ubuntu1804安装Postgresql【转】下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

SpringBoot集成Druid实现数据源管理和监控

 1、添加Maven依赖 <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId>...

百度地图 infoBox的用法

var myIcon = new BMap.Icon("image/red.gif", new BMap.Size(23, 25), { offset: new BMap.Size(0, 0)}); var marker = new BMap.Marker(point,{icon:myIcon}); map.addOverlay(marker); var...

Requests方法 -- Token获取操作

获取token和code流程如下:a、先登陆抓包查看post(提交表单操作)头中是否有token和code关键字b、已知步骤a中出现了token和code,不登录前刷新登陆页面,查看response中是否有token和code关键字c、输入账号密码后查看登陆后的请求头中token和code是否与未登陆前response中的一致(锁定后就好操作了) 1、打开...

LinQ 入门系列 [OfType,ToArray,ToList,ToDictionary]

先说点理论1.OfType :     即接受基于IEnumerable<T> 接口的信息源,也接受那些在 .NET Framework 1.0 中出现的非参数化的 IEnumerable 接口(non-parameterized IEnumerable interface)。OfType 操作符允许用户在标准的 .NET collection...

ORA-00604的解决方法

分类: Oracle 从错误的角度可以推出:应该是表空间不足   根据查看表空间的使用情况: select b.file_name 物理文件名, b.tablespace_name 表空间, b.bytes/1024/1024 大小M, (b.bytes-sum(nvl(a.bytes,0)))/1024/1024 已使用M, substr((b.by...

oracle正则表达式函数 匹配

文章介绍了关于oracle正则函数的一些用法,包括匹配等,Oracle10g提供了在查询中使用正则表达的功能,它是通过各种支持正则表达式的函数在where子句中实现的。 ORACLE中的支持正则表达式的函数主要有下面四个: 1,REGEXP_LIKE :与LIKE的功能相似 2,REGEXP_INSTR :与INSTR的功能相似 3,REGEXP_SU...