3.0 KiB
3.0 KiB
In [4]:
import torch import torch.nn as nn
In [8]:
input_feat = torch.tensor([[4, 1, 7, 5], [4, 4, 2, 5], [7, 7, 2, 4], [1, 0, 2, 4]], dtype=torch.float32).unsqueeze(0).unsqueeze(0) print(input_feat) print(input_feat.shape)
tensor([[[[4., 1., 7., 5.],
[4., 4., 2., 5.],
[7., 7., 2., 4.],
[1., 0., 2., 4.]]]])
torch.Size([1, 1, 4, 4])
In [16]:
conv2d = nn.Conv2d(1, 1, (2, 2), stride=1, padding='same', bias=False) # 卷积核要有四个维度:输出通道数,输入通道数,卷积核高度,卷积核宽度 kernels = torch.tensor([[[[1, 0], [2, 1]]]], dtype=torch.float32) conv2d.weight = nn.Parameter(kernels, requires_grad=False) # 设置卷积核 # 默认情况随机初始化参数 print(conv2d.weight) print(conv2d.bias)
Parameter containing:
tensor([[[[1., 0.],
[2., 1.]]]])
None
In [17]:
output = conv2d(input_feat) output
Out[17]:
tensor([[[[16., 11., 16., 15.],
[25., 20., 10., 13.],
[ 9., 9., 10., 12.],
[ 1., 0., 2., 4.]]]])