栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

目录

一、Linear函数的官方文档

二、实例练习

1.使用reshape函数

2.使用flatten函数

2.1 torch.flatten()的官方文档

2.2 flatten的实例练习

总结


一、Linear函数的官方文档

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()

2.1 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

2.2 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功能更加强大。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/949721.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号