The Wayback Machine - https://web.archive.org/web/20240707135854/https://www.geeksforgeeks.org/what-is-transposed-convolutional-layer/
Open In App

What is Transposed Convolutional Layer?

Last Updated : 24 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A transposed convolutional layer is an upsampling layer that generates the output feature map greater than the input feature map. It is similar to a deconvolutional layer. A deconvolutional layer reverses the layer to a standard convolutional layer. If the output of the standard convolution layer is deconvolved with the deconvolutional layer then the output will be the same as the original value, While in transposed convolutional value will not be the same, it can reverse to the same dimension,

Transposed convolutional layers are used in a variety of tasks, including image generation, image super-resolution, and image segmentation. They are particularly useful for tasks that involve upsampling the input data, such as converting a low-resolution image to a high-resolution one or generating an image from a set of noise vectors. 

The operation of a transposed convolutional layer is similar to that of a normal convolutional layer, except that it performs the convolution operation in the opposite direction. Instead of sliding the kernel over the input and performing element-wise multiplication and summation, a transposed convolutional layer slides the input over the kernel and performs element-wise multiplication and summation. This results in an output that is larger than the input, and the size of the output can be controlled by the stride and padding parameters of the layer.

Transposed Convolutional  with stride 2 - Geeksforgeeks

Transposed Convolutional  with stride 2

In a transposed convolutional layer, the input is a feature map of size  I_h \times I_w     , where  I_h      and  I_w   are the height and width of the input and the kernel size is  K_h \times K_w , where K_h  and  K_w   are the height and width of the kernel. 

 If the stride shape is (s_h,s_w)   and the padding is p, The stride of the transposed convolutional layer determines the step size for the input indices p and q, and the padding determines the number of pixels to add to the edges of the input before performing the convolution. Then the output of the transposed convolutional layer will be

O_h = (I_h -1) \times s_h + K_h -2p \\ O_w = (I_w -1) \times s_w + K_h -2p

where O_h   and O_w  are the height and width of the output.

Example 1: 

Suppose we have a grayscale image of size 2 X 2, and we want to upsample it using a transposed convolutional layer with a kernel size of 2 x 2, a stride of 1, and zero padding (or no padding). The input image and the kernel for the transposed convolutional layer would be as follows:

Input = \begin{bmatrix} 0 & 1\\ 2 & 3 \end{bmatrix}

Kernel = \begin{bmatrix} 4 & 1\\ 2 & 3 \end{bmatrix}

The output will be:

Transposed Convolutional  Stride = 1 -Geeksforgeeks

Transposed Convolutional  Stride = 1

Method 1: Manually with TensorFlow

Code Explanations:

  • Import necessary libraries (TensorFlow and NumPy)
  • Define Input tensor and custom kernel
  • Apply Transpose convolution with kernel size =2, stride = 1.
  • Write the custom functions for transpose convolution
  • Apply Transpose convolution on input data.

Python3

# Import Tensorflow
import tensorflow as tf
import numpy as np
 
# Input
Input = tf.constant([[0.0, 1.0], [2.0, 3.0]], dtype=tf.float32)
# Kernel
Kernel = tf.constant([[4.0, 1.0], [2.0, 3.0]], dtype=tf.float32)
# Define the transpose convolution function
 
 
def trans_conv(Input, Kernel):
    h, w = Kernel.shape
    Y = np.zeros((Input.shape[0] + h - 1, Input.shape[1] + w - 1))
 
    for i in range(Input.shape[0]):
        for j in range(Input.shape[1]):
            Y[i: i + h, j: j + w] += Input[i, j] * Kernel
    return tf.constant(Y)
 
 
# OUTPUT
trans_conv(Input, Kernel)

                    

Output:

<tf.Tensor: shape=(3, 3), dtype=float64, numpy=
array([[ 0.,  4.,  1.],
       [ 8., 16.,  6.],
       [ 4., 12.,  9.]])>

The output shape can be calculated as :

 \begin{aligned}O_h &= (I_h -1) \times s_h + K_h -2p \\ &= (2-1)\times 1 + 2 -2\times0 \\ &= 1\times 1 + 2-0 \\ &=3\end{aligned} \\ \begin{aligned}O_w &= (I_w -1) \times s_w + K_w -2p \\ &= (2-1)\times 1 + 2 -2\times0 \\ &= 1\times 1 + 2-0 \\ &=3\end{aligned}

Method 2: With PyTorch:

Code Explanations:

  • Import necessary libraries (torch and nn from torch)
  • Define Input tensor and custom kernel
  • Redefine the shape in 4 dimensions because PyTorch takes 4D shapes in inputs.
  • Apply Transpose convolution with input and output channel =1,1, kernel size =2, stride = 1, padding = 0 means valid padding.
  • Set the customer kernel weight by using Transpose.weight.data
  • Apply Transpose convolution on input data.

Python3

# Import the necessary module
import torch
from torch import nn
 
# Input
Input = torch.tensor([[0.0, 1.0], [2.0, 3.0]])
#Kernel
Kernel = torch.tensor([[4.0, 1.0], [2.0, 3.0]])
 
# Redefine the shape in 4 dimension
Input = Input.reshape(1, 1, 2, 2)
Kernel = Kernel.reshape(1, 1, 2, 2)
 
# Transpose convolution Layer
Transpose = nn.ConvTranspose2d(in_channels =1,
                               out_channels =1,
                               kernel_size=2,
                               stride = 1,
                               padding=0,
                               bias=False)
 
# Initialize Kernel
Transpose.weight.data = Kernel
# Output value
Transpose(Input)

                    

Output:

tensor([[[[ 0.,  4.,  1.],
          [ 8., 16.,  6.],
          [ 4., 12.,  9.]]]], grad_fn=<ConvolutionBackward0>)

Transposed convolutional layers are often used in conjunction with other types of layers, such as pooling layers and fully connected layers, to build deep convolutional networks for various tasks.

Example 2: Valid Padding

In valid padding, no extra layer of zeros will be added.

Python3

import tensorflow as tf
 
# Define the input tensor
input_tensor = tf.constant([[
    [[1, 2, 3], [5, 6, 7], [9, 10, 11], [13, 14, 15]],
    [[17, 18, 19], [21, 22, 23], [25, 26, 27], [29, 30, 31]],
    [[33, 34, 35], [37, 38, 39], [41, 42, 43], [45, 46, 47]],
    [[49, 50, 51], [53, 54, 55], [57, 58, 59], [61, 62, 63]]
]], dtype=tf.float32)
 
 
# Define the transposed convolutional layer
transposed_conv_layer = tf.keras.layers.Conv2DTranspose(
    filters=1, kernel_size=3, strides=2, padding='valid')
 
# Apply the transposed convolutional layer to the input tensor
output = transposed_conv_layer(input_tensor)
 
# Print the output shape
print(output.shape)

                    

Output:

(1, 9, 9, 1)

Example 3: Same Padding

In same padding, an Extra layer of zeros (known as the padding layer) will be added.

Python3

import tensorflow as tf
 
# Define the input tensor
input_tensor = tf.constant([[
    [[1, 2, 3], [5, 6, 7], [9, 10, 11], [13, 14, 15]],
    [[17, 18, 19], [21, 22, 23], [25, 26, 27], [29, 30, 31]],
    [[33, 34, 35], [37, 38, 39], [41, 42, 43], [45, 46, 47]],
    [[49, 50, 51], [53, 54, 55], [57, 58, 59], [61, 62, 63]]
]], dtype=tf.float32)
 
 
# Define the transposed convolutional layer
transposed_conv_layer = tf.keras.layers.Conv2DTranspose(
    filters=1, kernel_size=3, strides=2, padding='same')
 
# Apply the transposed convolutional layer to the input tensor
output = transposed_conv_layer(input_tensor)
 
# Print the output shape
print(output.shape)

                    

Output:

(1, 8, 8, 1)


Similar Reads

Fully Connected Layer vs Convolutional Layer
Confusion between Fully Connected Layers (FC) and Convolutional Layers is common due to terminology overlap. In CNNs, convolutional layers are used for feature extraction followed by FC layers for classification that makes it difficult for beginners to distinguish there roles. This article compares Fully Connected Layers (FC) and Convolutional Laye
4 min read
What is a 1D Convolutional Layer in Deep Learning?
Answer: A 1D Convolutional Layer in Deep Learning applies a convolution operation over one-dimensional sequence data, commonly used for analyzing temporal signals or text.A 1D Convolutional Layer (Conv1D) in deep learning is specifically designed for processing one-dimensional (1D) sequence data. This type of layer is particularly useful for tasks
2 min read
Apply a 2D Transposed Convolution Operation in PyTorch
Transposed convolution, also known as fractionally-strided convolution, is a technique used in convolutional neural networks (CNNs) for the upsampling layer that increases the spatial resolution of an image. It is similar to a deconvolutional layer. A deconvolutional layer reverses the layer to a standard convolutional layer. If the output of the s
7 min read
Applying Convolutional Neural Network on mnist dataset
CNN is basically a model known to be Convolutional Neural Network and in recent times it has gained a lot of popularity because of its usefulness. CNN uses multilayer perceptrons to do computational works. CNN uses relatively little pre-processing compared to other image classification algorithms. This means the network learns through filters that
6 min read
Depth wise Separable Convolutional Neural Networks
Convolution is a very important mathematical operation in artificial neural networks(ANN's). Convolutional neural networks (CNN's) can be used to learn features as well as classify data with the help of image frames. There are many types of CNN's. One class of CNN's are depth wise separable convolutional neural networks. These type of CNN's are wid
4 min read
Importance of Convolutional Neural Network | ML
Convolutional Neural Network as the name suggests is a neural network that makes use of convolution operation to classify and predict. Let's analyze the use cases and advantages of a convolutional neural network over a simple deep learning network. Weight sharing: It makes use of Local Spatial coherence that provides same weights to some of the edg
2 min read
Deep Convolutional GAN with Keras
Deep Convolutional GAN (DCGAN) was proposed by a researcher from MIT and Facebook AI research. It is widely used in many convolution-based generation-based techniques. The focus of this paper was to make training GANs stable. Hence, they proposed some architectural changes in the computer vision problems. In this article, we will be using DCGAN on
9 min read
Deep parametric Continuous Convolutional Neural Network
Deep Parametric Continuous Kernel convolution was proposed by researchers at Uber Advanced Technologies Group. The motivation behind this paper is that the simple CNN architecture assumes a grid-like architecture and uses discrete convolution as its fundamental block. This inhibits their ability to perform accurate convolution to many real-world ap
6 min read
Convolutional Neural Network (CNN) Architectures
Convolutional Neural Network(CNN) is a neural network architecture in Deep Learning, used to recognize the pattern from structured arrays. However, over many years, CNN architectures have evolved. Many variants of the fundamental CNN Architecture This been developed, leading to amazing advances in the growing deep-learning field. Let's discuss, How
11 min read
Convolutional Block for Image Recognition
INTRODUCTION: The basic neural network design i.e. an input layer, few dense layers, and an output layer does not work well for the image recognition system because objects can appear in lots of different places in an image. So the solution is to add one or more convolutional layers. A convolutional block is a building block used in a convolutional
5 min read