一、Linear Layers
torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)
以VGG神经网络为例,Linear Layers可以将特征图的大小进行变换由(1,1,4096)转换为(1,1,1000)
二、torch.nn.Linear实战
将CIFAR-10数据集中的测试集二维图像[64, 3, 32, 32]通过线性神经网络,转换为[1, 1, 1, 10]形式
import torchvision
import torch.nn
from torch import nn
from torch.nn import Linear
from torch.utils.data import DataLoaderdataset_testset = torchvision.datasets.CIFAR10("CIFAR_10",train=False,transform=torchvision.transforms.ToTensor(),download=True)dataloader = DataLoader(dataset_testset,batch_size=64)class Beyond(nn.Module):def __init__(self):super(Beyond,self).__init__()self.linear_1 = Linear(196608,10)#因为原始图片是[64, 3, 32, 32],通过reshape转换为[1, 1, 1, 196608]#输入为196608,输出这里设置成10def forward(self,input):output = self.linear_1(input)return outputbeyond = Beyond()i = 0
for data in dataloader:imgs,targets = data#查看CIFAR-10数据集中图片的大小print(imgs.shape)#torch.Size([64, 3, 32, 32])"""方法一:#转换为一维形式output = torch.reshape(imgs,(1,1,1,-1))print(output.shape)#torch.Size([1, 1, 1, 196608])"""#方法二:#flatten可以将输入的数据变成一行output = torch.flatten(imgs)print(output.shape)#torch.Size([196608])#通过线性层神经网络output = beyond(output)print(output.shape)#torch.Size([1, 1, 1, 10])