我试着用tf.GradientTape来计算梯度。当我尝试这样做时,使用loss和Model.variables (tf.keras.Model)作为输入,这是一个返回None数组的结果。我做错了什么?我使用的tensorflow版本是1.9。
Model = CubeValModel(TrainingCurves)
LearningRate = 0.0005
TrainOpe = tf.train.AdamOptimizer(LearningRate, name="MainTrainingOpe")
for i in range (5):
with tf.GradientTape() as t:
Predictions = tf.nn.softmax(Model.FinalFC, name="SoftmaxPredictions")
Cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=Predictions, labels=TrainingLabels, name="CrossEntropy")
Loss = tf.reduce_mean(Cross_entropy, name="Loss")
print (Loss)
print (Model.variables)
Gradients = t.gradient(Loss, Model.variables)
print(Gradients)输出:
tf.Tensor(0.84878147, shape=(), dtype=float32)
[<tf.Variable 'LayerBlock1/Weights1:0' shape=(1, 3, 1, 3) dtype=float32, numpy=
[None, None, None, None, None, None, None, None, None]发布于 2018-08-24 21:02:52
我假设您使用的是TensorFlow eager,不是吗?如果我没记错的话,在tf.GradientTape()下,您应该调用计算模型的方法,而不是调用它的一个成员。这个计算执行将允许t计算出它需要在以后生成哪些梯度。我希望这能帮到你
https://stackoverflow.com/questions/51994043
复制相似问题