使用VGG19模型损失计算梯度时出错

时间:2019-05-08 18:32:26

标签: python tensorflow keras

我的目标是针对VGG损耗计算梯度。为此,我创建了我的模型,在其中定义了自定义损耗,该损耗是使用VGG第4卷积块的输出计算得出的。

当我使用python example.py运行tensorflow脚本时,出现错误:

ValueError: No gradients provided for any variable:

我认为发生这种情况是因为我的模型变量在VGG损失方面是不可区分的(因为VGG模型是一个独立的网络)。

总而言之,在给定输入x的情况下,我使用解码器模型重构了图像以得到图像y_pred。然后,我想对VGG网络进行计算并最大程度地减少损失。

我的代码如下:

example.py

import tensorflow as tf
import numpy as np 
from tensorflow.keras.applications import VGG19
from tensorflow.keras.layers import Input, UpSampling2D, Conv2D
from tensorflow.keras.models import Model
import tensorflow.keras.backend as K
from tensorflow.keras.optimizers import Adam

class CustomModel:

    def __init__(self, im_h, im_w, im_c):
        self.im_shape = (im_h, im_w, im_c)
        self.vgg_features_shape = (None, None, 512)
        self.vgg_loss_model = self.build_vgg_loss()
        self.kernel_size = (3,3)
        self.decoder = self.build_decoder()


    def build_vgg_loss(self):
        vgg = VGG19(weights="imagenet", include_top=False, input_shape=self.im_shape)
        vgg.outputs = [
            vgg.get_layer('block1_conv1').output,
            vgg.get_layer('block2_conv1').output,
            vgg.get_layer('block3_conv1').output,
            vgg.get_layer('block4_conv1').output
        ]

        model = Model(inputs=vgg.inputs, outputs=vgg.outputs)
        model.trainable = False

        return model

    def build_decoder(self):
        """
        Mirrors the VGG network with max-pooling layers replaces by UpScaling Layers
        """

        i = Input((None, None, 512))
        x = Conv2D(filters=512, kernel_size=self.kernel_size, padding='same')(i)

        x = UpSampling2D()(x)
        for _ in range(4):
            x = Conv2D(filters=256, kernel_size=self.kernel_size, padding='same')(x)

        x = UpSampling2D()(x)
        for _ in range(2):
            x = Conv2D(filters=128, kernel_size=self.kernel_size, padding='same')(x)

        x = UpSampling2D()(x)
        for _ in range(2):
            x = Conv2D(filters=64, kernel_size=self.kernel_size, padding='same')(x)

        x = Conv2D(filters=3, kernel_size=self.kernel_size, padding='same')(x)

        model = Model(inputs=i, outputs=x)

        return model


    def get_loss(self, y_pred, y):

        vgg_model = self.vgg_loss_model

        def content_loss(y_pred, y):

            dif = vgg_model(y)[3] - vgg_model(y_pred)[3]
            sq = K.square(dif)
            s = K.sum(sq, axis=-1)
            sqrt = K.sqrt(s)
            loss = K.sum(sqrt)
            return loss

        return content_loss(y_pred, y)

# start of the script 

tf.enable_eager_execution()

# create model
model = CustomModel(256,256,3)

# create tf.data.Dataset
output_types=(
    tf.float32,
    tf.float32
 )
output_shapes=(
    tf.TensorShape([None, None, None, None]),
    tf.TensorShape([None, None, None, None])
)

def gen():
    while True:
        yield np.random.randn(1, 32, 32, 512), np.random.randn(1, 256, 256,3) 

ds = tf.data.Dataset.from_generator(gen,
                                   output_types=output_types, 
                                   output_shapes=output_shapes)

opt = tf.train.AdamOptimizer(0.01)

# start training
losses = []
for x, y in ds.take(100):
    y_pred = model.decoder(x)

    with tf.GradientTape() as t:
        loss = model.get_loss(y_pred, y)

    grads = t.gradient(loss, model.decoder.variables)
    grads_and_vars = zip(grads, model.decoder.variables)
    opt.apply_gradients(grads_and_vars)
    losses.append(tf.reduce_sum(loss))
    print(losses)

print('Done!')

0 个答案:

没有答案