I'm studying pytorch Conv2d package, for convolution filter. I coded like below, to check what the Conv2d function exactly do to image. And I found that the image filtered by conv2d looks different at every try, randomly. Just like the picture attached. So I've got questions like this.
below is the code.
from matplotlib import pyplot
from numpy import asarray
import numpy as np
import cv2
import torch
import torch.nn as nn
img = cv2.imread('data/dog.jpg') # 29 *30 *3
data = asarray(img)
conv1 = nn.Conv2d(3,1,3)
pyplot.subplot(1,2,2)
data = np.transpose(data, (2,0,1))
data = conv1(torch.Tensor(data))
data = np.transpose(data.detach().numpy(), (1,2,0))
pyplot.imshow(data, cmap='gray')
pyplot.show()
Just add the following code and it will work with the same weights every time.
torch.manual_seed(0)
Everytime you initialize Conv2D
layer, it is initialized with random weights. But setting PyTorch's manual_seed
to a constant number generates the same sequence of random numbers every time you run your code. This is what Reproducibility aims for. You can check PyTorch's reproducibility reference for more information regarding that topic.
TQCH's code helps you check out the weights every time you run your code. You will notice that the weights change every time you run print(conv1.weight)
. And you will also notice that they do not change every time you run the code if you specify the manual seed