Get startedGet started for free

Building a U-Net: forward method

With the encoder and decoder layers defied, you can now implement the forward() method of the U-net. The inputs have already been passed through the encoder for you. However, you need to define the last decoder block.

The goal of the decoder is to upsample the feature maps so that its output is of the same height and width as the U-Net's input image. This will allow you to obtain pixel-level semantic masks.

This exercise is part of the course

Deep Learning for Images with PyTorch

View Course

Exercise instructions

  • Define the last decoder block, using torch.cat() to form the skip connection.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

def forward(self, x):
    x1 = self.enc1(x)
    x2 = self.enc2(self.pool(x1))
    x3 = self.enc3(self.pool(x2))
    x4 = self.enc4(self.pool(x3))

    x = self.upconv3(x4)
    x = torch.cat([x, x3], dim=1)
    x = self.dec1(x)

    x = self.upconv2(x)
    x = torch.cat([x, x2], dim=1)
    x = self.dec2(x)

    # Define the last decoder block with skip connections
    x = ____
    x = ____
    x = ____

    return self.out(x)
Edit and Run Code