【PyTorch】To understand nn.Conv1d
1. nn.Conv1d
nn.Conv1d is a pytorch's class for execute 1 dimentional convolution.
・1DCNN
input_example = torch.randn(1, 1, 5) # batch_size, in_channels, sequence_length
conv1d = nn.Conv1d(in_channels=1, out_channels=3, kernel_size=3, stride=1, padding=1)
The primary aurgment is this:
in_channels: Number of channels in the input tensor(signal)
out_channels: Number of output channels(feature map)
kernel_size: The size of convolutional kernel
stride: The stride of the convolution. defalut=1
padding: The number of padding added to the input tensor. default=0, 1dcnn provide same output length as input length when padding='same'
.
2. Try to use
2.1 Example
Let's see the behaviour of 1DCNN with a test code.
import torch
import torch.nn as nn
# Define the input tensor
input_tensor = torch.randn(1, 1, 5) # batch_size, in_channels, sequence_length
# Define the Conv1d layer
conv1d = nn.Conv1d(in_channels=1, out_channels=3, kernel_size=3, stride=1, padding=1)
# Apply the Conv1d operation
output_tensor = conv1d(input_tensor)
print("Input tensor shape:", input_tensor.shape)
print("Output tensor shape:", output_tensor.shape)
### output
# Input tensor shape: torch.Size([1, 1, 5])
# Output tensor shape: torch.Size([1, 3, 5])
2.2 How adjust output
In this convolution change the shape of input[1, 1, 5] to output[1, 3, 5]. It increase number of channel, but the length is not changed(5→5), we can specify the number of output channel by out_channels setting. The number of kernel is icreased then as you increase output_channels.
If you wanna specify output length, you should calculate the below formula from convolution's principle(or you can use padding='same' to align the size of input and output).
output_size = (input_size - kernel_size + 2 * padding) / stride + 1
3. Summary
This time, I explained about how to use the 1DCNN in the pytorch library.
Reference
[1] Conv1d, PyTorch
Discussion