tensorflow求导和梯度计算

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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值