Почему K.gradients не возвращает ничего для градиента потерь по сравнению с вводом - PullRequest
1 голос
/ 17 апреля 2020

Мне интересно, почему я не получаю ни одного за мои оценки в следующем коде:

import tensorflow.keras.losses as losses
loss = losses.squared_hinge(y_true, y_pred)

from tensorflow.keras import backend as K
grads = K.gradients(loss, CNN_model.input)[0]
iterate = K.function([CNN_model.input], [loss, grads])

мой CNN_model.input: <tf.Tensor 'conv2d_3_input:0' shape=(?, 28, 28, 1) dtype=float32>

моя потеря: <tf.Tensor 'Mean_3:0' shape=(1,) dtype=float64>

Примечание. Я передаю прогнозируемый вывод SVM как y_pred для моего приложения, если это важно.

1 Ответ

2 голосов
/ 17 апреля 2020

Насколько я понял из моего предыдущего опыта, Tensorflow должен использовать GradientTape для записи активности определенной переменной и для вычисления ее градиентов. В вашем случае должно быть что-то подобное:

x = np.random.rand(10) #your input variable
x = tf.Variable(x) #to be evaluated by GradientTape the input should be a tensor
with tf.GradientTape() as tape:
    tape.watch(x) #with this method you can observe your variable
    proba = model(x) #get the prediction of the input
    loss = your_loss_function(y_true, proba) #compute the loss

gradient = tape.gradient(loss, x) #compute the gradients, this must be done outside the recording
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...