TensorFlow 中切片输入的梯度为 None

时间:2021-02-17 05:55:44

标签: python tensorflow machine-learning deep-learning gradienttape

以下是我的代码

import tensorflow as tf
import numpy as np
def forward(x):
  z = tf.Variable(tf.zeros_like(x), trainable=False)
  s = tf.shape(x)[0]
  for i in range(s):
    z[i].assign(x[i]**i)
  return z

a = tf.Variable(np.ones([5])*3)

with tf.GradientTape() as tape:
  b = forward(a)
grad = tape.gradient(b, a)

我有一个输入,我必须对其进行切片,然后计算输出。在此基础上,我需要计算梯度。但是,上面代码的输出是None。

如何获得梯度?有什么方法可以切片输入以获得渐变。

附言我必须只使用 EagerExecution。无图形模式。

1 个答案:

答案 0 :(得分:1)

在使用gradientTape时,如果您将其视为一个函数会很有帮助。假设您的成本函数是 y = x ** 2。可以计算 y(您的函数)相对于 x(您的变量)的梯度。

在您的代码中,您没有计算梯度的函数。您试图计算针对变量的梯度,但不起作用。

我做了一个小改动。检查下面代码中的可变成本

import tensorflow as tf
import numpy as np
def forward(x):
  cost = []  
  z = tf.Variable(tf.zeros_like(x), trainable=False)
  s = tf.shape(x)[0]
  for i in range(s):
    z[i].assign(x[i]**i)
    cost.append(x[i]**i)
  return cost

a = tf.Variable(np.ones([5])*3)

with tf.GradientTape() as tape:
  b = forward(a)
grad = tape.gradient(b, a)
print(grad)