Tensorflow.Keras: How to get gradient for an output class w.r.t a given input?
You can get that from the weight updates, not sure if it is the best approach
-Save the model
-Save the weights of the first layer
-Load the model and Compile the model with SGD w/o momentum
-Set all the weights = that of the previous model
-Train with the input and output i.e. the Array for epoch=1 and batch_size=1
-Get the weights again
-Calculate the respective gradient using two weights of 1st layer
-If Gradient is very small, it might become zero due to matching digits of both the weights
w0 = model.get_weights().copy()
w0_0 = w0[0]

optimizer = tf.keras.optimizers.SGD( learning_rate=0.01, momentum=0.0, nesterov=False, name=&quot;SGD&quot;)
model.compile(optimizer=optimizer, loss='mse')
model.fit(input, output, epochs=1, verbose=1, batch_size=1)

w0_new = model.get_weights().copy()
w0_0_new = w0_new[0]

'''
w_new = w0 - learning_rate * g
g = (w0 - w_new)/learning_rate
'''
grad = (w0_0 - w0_0_new)/0.01