我对 tensorflow 相当陌生,我看过一些教程,但我不知道 tf.gradients() 是如何工作的。如果我给它两个二维矩阵的输入,它将如何计算偏导数?我真的很困惑,如果有人可以的话请帮助我,这将是一个很大的帮助。
import tensorflow as tf
import numpy as np
X = np.random.rand(3,3)
y = np.random.rand(2,2)
grad = tf.gradients(X,y)
with tf.Session() as sess:
sess.run(grad)
print(grad)
这会产生错误:
回溯(最近一次调用最后一次): 文件“C:/Users/Sandeep IPK/PycharmProjects/tests/samples2.py”,第 10 行,位于 sess.run(毕业) 文件“C:\Users\Sandeep IPK\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py”,第 767 行,运行中 运行元数据指针) 文件“C:\Users\Sandeep IPK\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py”,第 952 行,在 _run 中 fetch_handler = _FetchHandler(self._graph, fetches, feed_dict_string) 文件“C:\Users\Sandeep IPK\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py”,第 408 行,init self._fetch_mapper = _FetchMapper.for_fetch(获取) 文件“C:\Users\Sandeep IPK\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py”,第 230 行,在 for_fetch 中 返回_ListFetchMapper(获取) 文件“C:\Users\Sandeep IPK\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py”,第 337 行,init self._mappers = [_FetchMapper.for_fetch(fetch) 用于在 fetches 中进行 fetch] 文件“C:\Users\Sandeep IPK\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py”,第 337 行,位于 self._mappers = [_FetchMapper.for_fetch(fetch) 用于在 fetches 中进行 fetch] 文件“C:\Users\Sandeep IPK\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py”,第 227 行,在 for_fetch 中 (获取,类型(获取))) 类型错误:获取参数 None 具有无效类型
进程已完成,退出代码为 1
最佳答案
TensorFlow 使用 reverse accumulation基于链式法则,计算该点的梯度值。为了计算函数相对于变量的梯度,您必须定义两者。此外,您还必须指定要计算梯度的值。在此示例中,您计算 y=x**2+x+1
相对于 x
在 2
处的梯度:
#!/usr/bin/env python3
import tensorflow as tf
x = tf.Variable(2.0)
y = x**2 + x - 1
grad = tf.gradients(y, x)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
grad_value = sess.run(grad)
print(grad_value)
# output: [5.0]
如果变量是矩阵,也可以计算梯度。在这种情况下,梯度也将是一个矩阵。这里我们使用一个简单的情况,当函数取决于所有矩阵元素的总和时:
#!/usr/bin/env python3
import tensorflow as tf
X = tf.Variable(tf.random_normal([3, 3]))
X_sum = tf.reduce_sum(X)
y = X_sum**2 + X_sum - 1
grad = tf.gradients(y, X)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
grad_value = sess.run(grad)
print(grad_value)
# output: [array([[ 9.6220665, 9.6220665, 9.6220665],
# [ 9.6220665, 9.6220665, 9.6220665],
# [ 9.6220665, 9.6220665, 9.6220665]], dtype=float32)]
关于python-3.x - tf.gradients() 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43934225/