tensorflow求导和梯度计算实例

作者:大雄没有叮当猫 时间:2023-08-09 14:07:38 

1. 函数求一阶导


import tensorflow as tf
tf.enable_eager_execution()
tfe=tf.contrib.eager
from math import pi
def f(x):
 return tf.square(tf.sin(x))
assert f(pi/2).numpy()==1.0
sess=tf.Session()
grad_f=tfe.gradients_function(f)
print(grad_f(np.zeros(1))[0].numpy())

2. 高阶函数求导


import numpy as np
def f(x):
 return tf.square(tf.sin(x))

def grad(f):
 return lambda x:tfe.gradients_function(f)(x)[0]

x=tf.lin_space(-2*pi,2*pi,100)
# print(grad(f)(x).numpy())
x=x.numpy()
import matplotlib.pyplot as plt
plt.plot(x,f(x).numpy(),label="f")
plt.plot(x,grad(f)(x).numpy(),label="first derivative")#一阶导
plt.plot(x,grad(grad(f))(x).numpy(),label="second derivative")#二阶导
plt.plot(x,grad(grad(grad(f)))(x).numpy(),label="third derivative")#三阶导
plt.legend()
plt.show()

def f(x,y):
 output=1
 for i in range(int(y)):
   output=tf.multiply(output,x)
 return output

def g(x,y):
 return tfe.gradients_function(f)(x,y)[0]

print(f(3.0,2).numpy()) #f(x)=x^2
print(g(3.0,2).numpy()) #f'(x)=2*x
print(f(4.0,3).numpy())#f(x)=x^3
print(g(4.0,3).numpy())#f(x)=3x^2

3. 函数求一阶偏导


x=tf.ones((2,2))
with tf.GradientTape(persistent=True) as t:
 t.watch(x)
 y=tf.reduce_sum(x)
 z=tf.multiply(y,y)

dz_dy=t.gradient(z,y)
print(dz_dy.numpy())
dz_dx=t.gradient(z,x)
print(dz_dx.numpy())
for i in [0, 1]:
for j in [0, 1]:
 print(dz_dx[i][j].numpy() )

4. 函数求二阶偏导


x=tf.constant(2.0)
with tf.GradientTape() as t:
 with tf.GradientTape() as t2:
   t2.watch(x)
   y=x*x*x
 dy_dx=t2.gradient(y,x)
d2y_dx2=t.gradient(dy_dx,x)

print(dy_dx.numpy())
print(d2y_dx2.numpy())

来源:https://blog.csdn.net/u013230189/article/details/81739520

标签:tensorflow,求导,梯度计算
0
投稿

猜你喜欢

  • php版微信支付api.mch.weixin.qq.com域名解析慢原因与解决方法

    2023-07-16 11:36:01
  • 软件测试面试如何测试网页的登录页面

    2023-12-10 20:45:30
  • 梅尔倒谱系数(MFCC)实现

    2022-08-08 18:28:08
  • Python如何使用27行代码绘制星星图

    2024-01-02 10:41:44
  • 解决golang编译提示dial tcp 172.217.160.113:443: connectex: A connection attempt failed(推荐)

    2023-07-16 04:24:49
  • Python3 解释器的实现

    2023-08-09 17:08:53
  • Go Web 编程中的模板库应用指南(超详细)

    2024-02-05 20:50:55
  • python 从list中随机取值的方法

    2021-10-06 04:08:11
  • python django框架中使用FastDFS分布式文件系统的安装方法

    2022-02-25 21:27:33
  • python定时关机小脚本

    2022-09-24 23:38:21
  • python中requests模块的使用方法

    2021-12-27 23:16:29
  • 18个Python脚本可加速你的编码速度(提示和技巧)

    2022-11-09 16:54:34
  • 使用python删除nginx缓存文件示例(python文件操作)

    2021-10-16 03:41:32
  • Python基于yield遍历多个可迭代对象

    2023-01-05 23:01:32
  • 用JS找出字符串中出现次数最多的字母

    2007-11-12 13:40:00
  • Golang实现常见排序算法的示例代码

    2024-02-16 12:49:10
  • pydantic进阶用法示例详解

    2022-01-31 07:00:03
  • Python学习笔记之迭代器和生成器用法实例详解

    2021-07-15 21:25:04
  • MySQL增删查改数据表详解

    2024-01-25 06:55:48
  • python爬虫selenium和phantomJs使用方法解析

    2023-02-06 19:23:38
  • asp之家 网络编程 m.aspxhome.com