神经网络的基本框架

import torch
import torch.nn as nn


class Model(nn.Module):
    def __init__(self) -> None:
        super().__init__()

    def forward(self, input):
        output = input + 1
        return output


model = Model()
x = torch.tensor(1.0)
output = model(x)
print(output)

首先,我们要用到torch.nn这个库,里面包含了神经网络的基本框架和卷积层,池化层等。基本流程就是先建立一个关于自己所要构造的神经网络模型类,该类要继承Module类,实行改写来得到自己的神经网络模型。

卷积函数:

 首先卷积函数来自于torch.nn.functional,我们一般常用con2d这个函数。

import torch
import torch.nn.functional as F

x = 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]])

x = torch.reshape(x, (1, 1, 5, 5))
kernel = torch.reshape(kernel, (1, 1, 3, 3))
output = F.conv2d(x, kernel, stride=1, padding=1)
print(output)

conv2d这个函数的第一个参数为Input,输入的类型必须为张量,且尺寸要求为(minbatch,channel,H,W),第二个参数为kernel卷积核,输入的类型和尺寸如out_channels,in_channels​/groups,kH,kW,还有步长,padding和bias参数

卷积:

       用到了torch.nn里面的卷积类conv2d,

import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

test_set = torchvision.datasets.CIFAR10("./datasets", train=False, transform=torchvision.transforms.ToTensor())
data_loader = DataLoader(test_set, batch_size=64)


class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3, stride=1, padding=0)

    def forward(self, x):
        output = self.conv1(x)
        return output


my_model = Model()
writer = SummaryWriter("logs")
step = 0
for data in data_loader:
    imgs , target = data
    writer.add_images("imgs", imgs, step)
    output = my_model(imgs)
    writer.add_images("output", output,step)
    step = step + 1

首先,加载数据集,然后用dataloader对其进行批量处理,然后建了一个我们的神经网络框架,里面只包含一个卷积操作,conv2d类其构造方法包含参数有,输入通道,输出通道,卷积核大小(这里只需要给定卷积核大小就可以,里面的参数都是初始化好的,而且后面反向传播还是需要更新参数的),步长,padding,然后对类进行实例化,然后进行操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值