@10xAI answer is good but seems to missing the final part in computing the gradients.
You can do this easily with TensorFlow's Automatic Differentiation:
import tensorflow as tf
import numpy as np
def CompileDNN():
# Define architecture of Keras Model, Compile it
return model
def loss_function():
# Define loss function
return
# Trained TensorFlow Keras Model
model = CompileDNN()
# model.fit(...)
X = # Inputs/features
Y = # Outcomes
# Compile another Keras Model, but untrained
model_temp = CompileDNN()
with tf.GradientTape() as tape:
# Trained DNN weights
weights = model.get_weights()
# Add some small perturbation; here we add N(0, 1e-6) to each parameter
weights = [ w + np.random.normal(0., 1e-6, size=(w.shape)) for w in weights ]
# Set the new perturbed weights
model_temp.set_weights( weights )
# Compute outputs
Y_hat = model_temp(X, training=False)
# Compute loss and gradients
loss = loss_function(Y, Y_hat)
grads = tape.gradient(loss, model_temp.trainable_parameters)
grads
will then give you the gradients of the perturbed weights, and you should probably wrap the gradient-block in a loop and repeat this process several times to get the expected gradient of loss with a $N(0, 1e-6)$ perturbation.