渴望的tf.GradientTape()仅返回None

时间:2019-04-11 18:26:20

标签: tensorflow

我尝试使用Tensorflow在急切模式下计算梯度,但是 tf.GradientTape()仅返回None值。我不明白为什么。 渐变是在update_policy()函数中计算的。

该行的输出:

|___id___|_firstnumber_|_secondnumber_|
| 19564  |   234287    |    234288    | 

grads = tape.gradient(loss, self.model.trainable_variables)

这是代码。

{list}<class 'list'>:[None, None, ... ,None]

1 个答案:

答案 0 :(得分:3)

您的模型中没有前进通道。 location.replace()方法返回Model.predict()数组,而无需点击正向传递。看一下这个例子:

给出以下数据和模型:

numpy()

首先我们使用import tensorflow as tf import numpy as np x_train = tf.convert_to_tensor(np.ones((1, 2), np.float32), dtype=tf.float32) y_train = tf.convert_to_tensor([[0, 1]]) model = tf.keras.models.Sequential([tf.keras.layers.Dense(2, input_shape=(2, ))])

predict()

现在我们使用模型的输入:

with tf.GradientTape() as tape:
    logits = model.predict(x_train)
    print('`logits` has type {0}'.format(type(logits)))
    # `logits` has type <class 'numpy.ndarray'>
    xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_train, logits=logits)
    reduced = tf.reduce_mean(xentropy)
    grads = tape.gradient(reduced, model.trainable_variables)
    print('grads are: {0}'.format(grads))
    # grads are: [None, None]

因此,请使用模型的with tf.GradientTape() as tape: logits = model(x_train) print('`logits` has type {0}'.format(type(logits))) # `logits` has type <class 'tensorflow.python.framework.ops.EagerTensor'> xentropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_train, logits=logits) reduced = tf.reduce_mean(xentropy) grads = tape.gradient(reduced, model.trainable_variables) print('grads are: {0}'.format(grads)) # grads are: [<tf.Tensor: id=2044, shape=(2, 2), dtype=float32, numpy= # array([[ 0.77717704, -0.777177 ], # [ 0.77717704, -0.777177 ]], dtype=float32)>, <tf.Tensor: id=2042, # shape=(2,), dtype=float32, numpy=array([ 0.77717704, -0.777177 ], dtype=float32)>] (即__call__())进行前向传递,而不要使用model(x)