[英]How to take gradient in Tensorflow for VGG16
我是 TF 的初學者,這是我遇到的問題:
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)
我想在這個例子中采用漸變,但它沒有返回,請幫助我理解為什么。
這是正確的方法
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.