#nn_conv#
import torch from torch import nn from torch.nn import Conv2d import torch.nn.functional as F import torchvision from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter """ 输入图像 -> 卷积核计算 -> 卷积后的输出 torch.nn.functional.conv1d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) -> Tensor input (minibatch, in_channels, iH, iW): 输入 | weight (out_channels, in_channels/groups, kH, kW): 卷积核 bias: 偏置 | stride: 步径, int: 横向纵向移动都是这个数值, tuple横向纵向指定数值 padding: int, tuple, 在输入图像周围进行填充(默认填充0), default=0 torch.nn.functional.conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode="zeros") in_channels: 输入的图像 out_channels: int, 设定卷积核的数量以得到对应数量的输出(卷积核值不一定相等) kernel_size: int / tuple 卷积核大小 .shape(N, C, H, W) """ # ------------ basic ------------ input = 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]]) # 将形状改为conv需要的 input = torch.reshape(input, (1, 1, 5, 5)) kernel = torch.reshape(kernel, (1, 1, 3, 3)) output1 = F.conv2d(input, kernel, stride=1) print(output1) # stride=2 output2 = F.conv2d(input, kernel, stride=2) print(output2) # 进行填充 output3 = F.conv2d(input, kernel, stride=1, padding=1) print(output3) # ------------ ect ------------ test_set = torchvision.datasets.CIFAR10(root="D:/dev/python/pyWork/Season2/Stage1/data/myimg", train=False, transform=torchvision.transforms.ToTensor()) dataloader = DataLoader(test_set, batch_size=64) class Test(nn.Module): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.conv1 = Conv2d(3, 6, 3, 1, 0) def forward(self, x): x = self.conv1(x) return x test = Test() print(test) writer = SummaryWriter("../logs") i = 0 for data in dataloader: imgs, targets = data output = test(imgs) print(imgs.shape) print(output.shape) writer.add_images("input", imgs, i) output = torch.reshape(output, (-1, -3, 30, 30)) writer.add_images("output", output, i) i = i + 1 writer.close()