1.卷积操作
卷积演示动态图
2.conv2d()函数
import torch
from torch.nn import functional as f
input_tensor = torch.tensor([
[1, 2, 0, 3, 1],
[0, 1, 2, 3, 1],
[1, 2, 1, 0, 0],
[5, 2, 3, 1, 1],
[2, 1, 0, 1, 1]
])
kernel = torch.tensor([ # 卷积核
[1, 2, 1],
[0, 1, 0],
[2, 1, 0]
])
# 因为conv2d的输入format是(batch_size,channel,H,W)所以需要转换
input_tensor = torch.reshape(input_tensor, (1, 1, 5, 5))
kernel = torch.reshape(kernel, (1, 1, 3, 3))
output1 = f.conv2d(input=input_tensor, weight=kernel, stride=1)
print(output1)
# stride = 1,padding = 0时输出结果为:
# tensor([[[[10, 12, 12],
# [18, 16, 16],
# [13, 9, 3]]]])
output2 = f.conv2d(input=input_tensor, weight=kernel, stride=2)
print(output2)
# stride = 2,padding = 0时输出结果为:
# tensor([[[[10, 12],
# [13, 3]]]])
output3 = f.conv2d(input=input_tensor, weight=kernel, stride=1, padding=1)
print(output3)
# stride = 1,padding = 1时输出结果为:
# tensor([[[[ 1, 3, 4, 10, 8],
# [ 5, 10, 12, 12, 6],
# [ 7, 18, 16, 16, 8],
# [11, 13, 9, 3, 4],
# [14, 13, 9, 7, 4]]]])
3.Convolution Layers
3.1 torch.nn.Conv2d类介绍
3.2 参数介绍
3.3代码实战
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from torch import nn
from torch.utils.tensorboard import SummaryWriter
test_dataset = datasets.CIFAR10(root="datasets", train=False, transform=transforms.ToTensor(), download=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=64, shuffle=True, drop_last=False)
class My_module(nn.Module):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.conv2d = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3, stride=1, padding=0)
def forward(self, x):
output = self.conv2d(x)
return output
my_module = My_module()
print(my_module)
writer = SummaryWriter("conv2d")
step = 0
for data in test_loader:
imgs, labels = data
imgs_conv2d = my_module(imgs)
writer.add_images(tag="Before_Conv2d", img_tensor=imgs, global_step=step)
writer.add_images(tag="After_Conv2d", img_tensor=imgs_conv2d, global_step=step)
step += 1
writer.close()