Project - Introduction to Neural Style Transfer using Deep Learning & TensorFlow 2 (Art Generation Project)

15 / 18

Defining Loss Function

  • Let us now define the style loss and content loss for the input image. We would be using the style_targets and content_targets to do this.

  • To do this, we shall define a function style_content_loss and implement the following steps:

    • Store the content representation and gram matrices of the style representations of the input image.
    • Calculate the mean squared difference between the gram matrices of the respective layers of the input image from the target representations. Add these average squared distances and scale this loss with style_weight to obtain the style_loss.
    • Calculate the squared difference between the content representations of the input image from the target representations. Add these average squared distances and scale this loss with content_weight to obtain the content_loss.
    • Add the style_loss and content_loss to obtain the total loss loss.

Note:

  • tf.reduce_mean computes the mean of elements across dimensions of a tensor.

  • tf.add_n adds all input tensors element-wise.

INSTRUCTIONS
  • Use the following code:

    num_content_layers = len(content_layers)
    num_style_layers = len(style_layers)
    
    def style_content_loss(outputs):
        style_outputs = outputs['style']
        content_outputs = outputs['content']
        style_loss = tf.add_n([tf.reduce_mean(
                                    (style_outputs[name] - style_targets[name])**2) 
                                    for name in style_outputs.keys()] )
        style_loss *= style_weight / num_style_layers
        content_loss = tf.add_n([tf.reduce_mean(
                                    (content_outputs[name]-content_targets[name])**2) 
                                     for name in content_outputs.keys()])
        content_loss *= content_weight / num_content_layers
        loss = style_loss + content_loss
        return loss
    
Get Hint See Answer


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...