How to take gradient in Tensorflow for VGG16

Viewed 145

I am a starter in TF, and here is what problem I have encountered:

VGG16=tf.keras.applications.VGG16(
    include_top=True,
    weights="imagenet",
    classes=1000,
)

x=tf.convert_to_tensor(cats_vs_dogs_array[0][0], dtype=tf.float32)

with tf.GradientTape(persistent=True) as g:
  g.watch(x)
  y = VGG16(x)

last_convolutional_layer = VGG16.get_layer('block5_conv3')

dz_dx = g.gradient(last_convolutional_layer.output, VGG16.input) 


print(dz_dx)

I am tying to take gradient in this example but it returns none, please help me to understand why.

1 Answers

here the correct way to do it

VGG16=tf.keras.applications.VGG16(
    include_top=True,
    weights="imagenet",
    input_shape=(224, 224,3),
    classes=1000,
)

x = tf.constant(np.random.uniform(0,1, (1,224,224,3)))
intermediate = Model(VGG16.input, VGG16.get_layer('block5_conv3').output)

with tf.GradientTape() as g:
    g.watch(x)
    y = intermediate(x)

dz_dx = g.gradient(y, x) 

print(dz_dx.shape)
Related