Python 笔记 Pytorch nn_conv

#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()
  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值