Given a matrix with the shape (1,3, H, W), I wish to obtain its difference in x-direction by channels. I use the function F.conv2d as follows.
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
# the shape of bdx3 is 1X3X3X3
bdx3 = torch.Tensor([[[[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
],
[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
],
[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]]
]
])
class MyGradientx(nn.Module):
def __init__(self):
super(MyGradientx, self).__init__()
def forward(self, input):
output = F.conv2d(input, bdx30, padding=1)
return output
H = 4
W = 5
u = np.arange(0, 3*H*W).astype(np.float32).reshape(1, 3, 4,5)
u = torch.from_numpy(u)
print("this is u: \n", u)
net1 = MyGradientx()
u1 = net1(u)
print("this is u1: \n", u1, "\n u1 shape", u1.shape)
I get the results:
this is u:
tensor([[[[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.],
[10., 11., 12., 13., 14.],
[15., 16., 17., 18., 19.]],
[[20., 21., 22., 23., 24.],
[25., 26., 27., 28., 29.],
[30., 31., 32., 33., 34.],
[35., 36., 37., 38., 39.]],
[[40., 41., 42., 43., 44.],
[45., 46., 47., 48., 49.],
[50., 51., 52., 53., 54.],
[55., 56., 57., 58., 59.]]]])
this is u1:
tensor([[[[-1., -1., -1., -1., 4.],
[-1., -1., -1., -1., 9.],
[-1., -1., -1., -1., 14.],
[-1., -1., -1., -1., 19.]],
[[-1., -1., -1., -1., 24.],
[-1., -1., -1., -1., 29.],
[-1., -1., -1., -1., 34.],
[-1., -1., -1., -1., 39.]],
[[-1., -1., -1., -1., 44.],
[-1., -1., -1., -1., 49.],
[-1., -1., -1., -1., 54.],
[-1., -1., -1., -1., 59.]]]])
u1 shape torch.Size([1, 3, 4, 5])
The first problem is if there are some functions in pytorch for the difference to a matrix give the same results?
Thank you!