tensorflow检查op是否可导(反向传播)

来源:互联网 发布:人工智能的主要技术 编辑:程序博客网 时间:2024/05/18 09:09
1.安装最新版tf--tensorflow1.5,gpu版本需要CUDA8和cudnn6,命令如下
 GPU版:sudo pip3 install tf-nightly-gpu
 CPU版:sudo pip3 install tf-nightly
对应pip网站:https://pypi.python.org/pypi/tf-nightly-gpu
2.编写代码进行测试,主要包括可导函数square和不可导函数floor
代码参考网站https://research.googleblog.com/2017/10/eager-execution-imperative-define-by.html
代码示例:
import numpy as np
import tensorflow as tf
import tensorflow.contrib.eager as tfe

tfe.enable_eager_execution()
def floor(x):
  return tf.floor(x)

def square(x):
  return tf.multiply(x, x)

grad_f = tfe.gradients_function(floor)
print(floor(3.))    
print('gradient of floor:',grad_f(3.))

grad_s = tfe.gradients_function(square)
print(square(3.))
print('gradient of square:',grad_s([3.]))

代码输出:
tf.Tensor(3.0, shape=(), dtype=float32)
gradient of floor: [None]
tf.Tensor(9.0, shape=(), dtype=float32)
gradient of square: [<tf.Tensor: id=21, shape=(1,), dtype=float32, numpy=array([ 6.], dtype=float32)>]

3.小结
     可以看出,floor函数对应的梯度为None,而square函数对应的梯度为 derivative(x^2)=2*x|x=3=6
原创粉丝点击