这一节内容做的笔记有些潦草,但内容和代码都与前面的一致
a.代码如下(示例):
import torch
import torchvision
from torch import nn
from torch.nn import Linear
from torch.utils.data import DataLoader
dataset=torchvision.datasets.CIFAR10("./dataset",train=False,transform=torchvision.transforms.ToTensor(),
download=True)
dataloader=DataLoader(dataset,batch_size=64)
"""class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.linear1=Linear()"""
for data in dataloader:
imgs,targets=data
print(imgs.shape) #[64,3,32,32]
import torch
import torchvision
from torch import nn
from torch.nn import Linear
from torch.utils.data import DataLoader
dataset=torchvision.datasets.CIFAR10("./dataset",train=False,transform=torchvision.transforms.ToTensor(),
download=True)
dataloader=DataLoader(dataset,batch_size=64)
"""class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.linear1=Linear()"""
for data in dataloader:
imgs,targets=data
print(imgs.shape) #[64,3,32,32]
output=torch.reshape(imgs,[1,1,1,-1]) #将最后一个数让它自己计算
print(output.shape)
c.当调用函数时,代码如下:
import torch
import torchvision
from torch import nn
from torch.nn import Linear
from torch.utils.data import DataLoader
dataset=torchvision.datasets.CIFAR10("./dataset",train=False,transform=torchvision.transforms.ToTensor(),
download=True)
dataloader=DataLoader(dataset,batch_size=64)
class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.linear1=Linear(196608,10)
def forward(self,input):
output=self.linear1(input)
return output
tudui=Tudui()
for data in dataloader:
imgs,targets=data
print(imgs.shape) #[64,3,32,32]
output=torch.reshape(imgs,[1,1,1,-1]) #将最后一个数让它自己计算
print(output.shape)
output=tudui(output)
print(output.shape)
d.当我想用Flatten时,代码书写如下:
import torch
import torchvision
from torch import nn
from torch.nn import Linear
from torch.utils.data import DataLoader
dataset=torchvision.datasets.CIFAR10("./dataset",train=False,transform=torchvision.transforms.ToTensor(),
download=True)
dataloader=DataLoader(dataset,batch_size=64)
class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.linear1=Linear(196608,10)
def forward(self,input):
output=self.linear1(input)
return output
tudui=Tudui()
for data in dataloader:
imgs,targets=data
print(imgs.shape) #[64,3,32,32]
output=torch.flatten(imgs) #将输入层进行展平
print(output.shape)
output=tudui(output)
print(output.shape)
参考土堆老师的视频,做的笔记神经网络-线性层及其他层介绍_哔哩哔哩_bilibili