How to use Conv2d with PyTorch?

Chris Staff asked 6 months ago
1 Answers
Best Answer
Chris Staff answered 6 months ago

As follows. You add it to the layers structure in your neural network, which in PyTorch is an instance of a nn.Module. Conv2d layers are often the first layers. Two parameters are mandatory: the first, which declares the number of channels in your input data OR the number of feature maps generated by the previous Conv2d layer; the second, which tells PyTorch to output X feature maps in this layer. Below, we also use a kernel size of 3. Strides et cetera are also possible. A full attribute list can be found here: https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html

import os
import torch
from torch import nn
from torchvision.datasets import MNIST
from torch.utils.data import DataLoader
from torchvision import transforms

class ConvNet(nn.Module):
  '''
    Convolutional Neural Network
  '''
  def __init__(self):
    super().__init__()
    self.layers = nn.Sequential(
      nn.Conv2d(1, 5, kernel_size=3),
      nn.Flatten(),
      nn.Linear(26 * 26 * 5, 300),
      nn.ReLU(),
      nn.Linear(300, 64),
      nn.ReLU(),
      nn.Linear(64, 10)
    )


  def forward(self, x):
    '''Forward pass'''
    return self.layers(x)

Your Answer

9 + 5 =