目录
官方文档:Linear — PyTorch 1.13 documentation
CLASS torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)

每一层的某个神经元的值都为前一层所有神经元的值的sum和。
基于公式y=wx+b计算,w为权重,x为输入,b为偏置值。
Parameters:
Variables:
weight (torch.Tensor) – the learnable weights of the module of shape
bias – the learnable bias of the module of shape
我们想要像上图中vgg model那样,输入一个 1*1*x的向量,线性变换后输出一个1*1*y的向量,因此我们需要获取到输入向量的宽数值,然后自己设定想要输出的宽值y即可。
由于我们使用的数据集是cifar10,设置的batchsize=64,因此我们首先需要把图片集的(64,3,32,32)的大小使用reshape方法展平为(1,1,1,x)的大小,再作为输入向量输入神经网络中,x的大小可以在参数中设置为-1,让电脑为我们计算具体为多少值。
- dataset = torchvision.datasets.CIFAR10(root="./CIFAR10", train=False, transform=torchvision.transforms.ToTensor(),
- download=True)
- dataloader = DataLoader(dataset, batch_size=64)
输入的数据集的size参数为(64,3,32,32), torch.size()中的四个参数分别代表:(batch size, channel, height, width)。即一批图片共64张,每张图片三个通道,长*宽为32*32。
有两种方法可以将向量展平,reshape和flatten,reshape比flatten更加灵活,因为可以自己指定尺寸大小,flatten只能把向量拉平成一条直线。
我们想要将其转换为batchsize=1,每张图片一个通道,长为1,宽为未知的图片;因为未知宽,因此在使用reshape方法设置参数时即可把宽的数值设置为-1,让电脑自己进行计算。
- for data in dataloader:
- imgs, lables = data
- print(imgs.shape)
- out = torch.reshape(imgs, (1, 1, 1, -1))
- print(out.shape)
- for data in dataloader:
- imgs, lables = data
- print(imgs.shape)
- input = torch.flatten(imgs)
- print(input.shape)
- output = maweiyi(input)
- print(output.shape)

可以看到调整后的宽长度为196608。
设定Linear类中的in_feature和out_feature参数,前者为196608,后者我们想要输出一个宽为10的张量,因此设定为10。
- class Maweiyi(torch.nn.Module):
- def __init__(self):
- super(Maweiyi, self).__init__()
- self.linear1 = Linear(196608, 10)
-
- def forward(self, input):
- output = self.linear1(input)
- return output
- import torch
- import torchvision.datasets
- from torch.nn import Linear
- from torch.utils.data import DataLoader
-
- dataset = torchvision.datasets.CIFAR10(root="./CIFAR10", train=False, transform=torchvision.transforms.ToTensor(),
- download=True)
- dataloader = DataLoader(dataset, batch_size=64)
-
-
- class Maweiyi(torch.nn.Module):
- def __init__(self):
- super(Maweiyi, self).__init__()
- self.linear1 = Linear(196608, 10)
-
- def forward(self, input):
- output = self.linear1(input)
- return output
-
- maweiyi = Maweiyi()
-
- for data in dataloader:
- imgs, lables = data
- print(imgs.shape)
- input = torch.flatten(imgs)
- print(input.shape)
- output = maweiyi(input)
- print(output.shape)

可以看到输入的向量大小为64*3*32*32,展平后为1*1*1*196608,线性变化后为1*1*1*10,实现变换。