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

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

福利区:独学而无友,则孤陋而寡闻.加入机器学习与深度学习讨论QQ群(581789266),一块交流与探讨,共同成长和进步!

猜你喜欢

转载自blog.csdn.net/dlhlSC/article/details/78436396
今日推荐