神经网络——线性层中Linear函数及torch.flatten()的使用

线性层中Linear函数可以将输入的样本大小,输出成我们需要的大小,在构建神经网络是经常会使用到,torch.flatten(),可以将数据展成一维的,相比较reshape函数,使用更加方便。但总的来说torch.flatten()的功能还是比较单调,reshape功能更加强大。

一、Linear函数的官方文档

二、实例练习

1.使用reshape函数

2.使用flatten函数

2.1 torch.flatten()的官方文档

2.2 flatten的实例练习

torch.nn.Linear(in_features,
out_features,
bias=True,
device=None,
dtype=None)

参数注解:
in_features – 每个输入样本的大小

out_features – 每个输出样本的大小

bias——如果设置为 False,该层将不会学习附加偏差。 默认值:True

shape:
input: (, H_{in})(∗,Hin​) 其中 ∗ 表示任意数量的维度,包括无和 H_{in} = \text{in_features}Hin​=in_features。

output: (*, H_{out})(∗,Hout​) 其中除了最后一个维度之外的所有维度都与输入的形状相同,并且 H_{out} = \text{out_features}Hout​=out_features。

1.使用reshape函数

代码如下:

import torch.nn
import torchvision
from torch import nn
from torch.nn import Linear
from torch.utils.data import DataLoader

#使用CIFAR10数据集
dataset = torchvision.datasets.CIFAR10("./dataset", train=False, transform=torchvision.transforms.ToTensor(),
                                       download=True)
#使用数据迭代器,DataLoader,为模型输入数据
dataloader = DataLoader(dataset, batch_size=64, drop_last=True)

#搭建神经网络
class Test(nn.Module):
    def __init__(self):       #初始化方法
        super(Test, self).__init__()      #继承父类
        self.linear1 = Linear(196608, 10)         #使用linear函数

    def forward(self, input):            #正向传播
        output = self.linear1(input)
        return output

test = Test()            #创建网络,初始化

for data in dataloader:
    imgs, targets = data
    print(imgs.shape)         #torch.Size([64, 3, 32, 32])
    output = torch.reshape(imgs, (1, 1, 1, -1))    #使用reshape函数改变尺寸
    print(output.shape)        #torch.Size([1, 1, 1, 196608])
    output = test(output)      #运用模型
    print(output.shape)         #torch.Size([1, 1, 1, 10])

输出结果:
torch.Size([64, 3, 32, 32])
torch.Size([1, 1, 1, 196608])
torch.Size([1, 1, 1, 10])

2.使用flatten函数

上面代码改变数据尺寸是使用torch.reshape()的,reshape可以由torch.reshape(),也可由torch.Tensor.reshape()调用
其作用是在不改变tensor元素数目的情况下改变tensor的shape。

如果使用torch.flatten(), 改变尺寸可以更加简单可以更加简单,代码如下:

for data in dataloader:
    imgs, targets = data
    print(imgs.shape)         #torch.Size([64, 3, 32, 32])
    output = torch.flatten(imgs)
    print(output.shape)        #torch.Size([196608])
    output = test(output)
    print(output.shape)         #torch.Size([10])

输出结果:
torch.Size([64, 3, 32, 32])
torch.Size([196608])
torch.Size([10])

下面我们来系统的学习一下torch.flatten()

torch.flatten(input, start_dim=0, end_dim=- 1) → Tensor

Parameters
input (Tensor) – the input tensor.

start_dim (int) – the first dim to flatten
end_dim (int) – the last dim to flatten

torch.flatten()输入是tensor
它的作用就是将输入tensor的第start_dim维到end_dim维之间的数据”拉平”成一维tensor,

torch.nn.Flatten()可以理解为一种网络结构,类似Conv2d、Linear。一般放在卷积层和全连接层之间,将卷积层输出”拉平”成一维。

练习代码如下:

import torch
from torch import nn

input = torch.tensor([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[1, 2, 2],
[3, 4, 4],
[5, 6, 6]]])

print(input)
output1 = torch.flatten(input, 0, 1)
print(output1)
output2 = torch.flatten(input, 1 , 2)
print(output2)
output3 = torch.flatten(input, 0 ,2 )
print(output3)

输出结果:
tensor([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[1, 2, 2],
[3, 4, 4],
[5, 6, 6]]])
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 2, 2],
[3, 4, 4],
[5, 6, 6]])
tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 2, 3, 4, 4, 5, 6, 6]])
tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 2, 3, 4, 4, 5, 6, 6])

线性层中Linear函数可以将输入的样本大小,输出成我们需要的大小,在构建神经网络是经常会使用到,torch.flatten(),可以将数据展成一维的,相比较reshape函数,使用更加方便。但总的来说torch.flatten()的功能还是比较单调,reshape功能更加强大。

Original: https://blog.csdn.net/m0_51816252/article/details/125113557
Author: 晓亮.
Title: 神经网络——线性层中Linear函数及torch.flatten()的使用

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/777559/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球