Pytorch深度学习-----神经网络之线性层用法

系列文章目录

PyTorch深度学习------Anaconda和PyTorch安装
Pytorch深度学习-----数据模块Dataset类
Pytorch深度学习------TensorBoard的使用
Pytorch深度学习------Torchvision中Transforms的使用(ToTensor,Normalize,Resize ,Compose,RandomCrop)
Pytorch深度学习------torchvision中dataset数据集的使用(CIFAR10)
Pytorch深度学习-----DataLoader的用法
Pytorch深度学习-----神经网络的基本骨架-nn.Module的使用
Pytorch深度学习-----神经网络的卷积操作
Pytorch深度学习-----神经网络之卷积层用法详解
Pytorch深度学习-----神经网络之池化层用法详解及其最大池化的使用
Pytorch深度学习-----神经网络之非线性激活的使用(ReLu、Sigmoid)


文章目录


一、线性层是什么?

线性层是深度学习中常用的一种基本层类型。它也被称为全连接层或仿射层。线性层的作用是将输入数据与权重矩阵相乘,然后加上偏置向量,最后输出一个新的特征表示。

具体来说,线性层可以表示为 Y = XW + b,其中 X 是输入数据W 是权重矩阵b 是偏置向量Y 是输出结果。这个过程可以看作是对输入数据进行线性变换的操作。

1.官网解释

官网访问:LINEAR

如下图所示

由此可见,每一层的某个神经元的值都为前一层所有神经元的值的总和。

2.nn.Linear函数参数介绍

python 复制代码
torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)

其中最重要的三个参数为in_features, out_features, bias

in_features, 表示输入的特征值大小,即输入的神经元个数
out_features,表示输出的特征值大小,即经过线性变换后输出的神经元个数
bias,表示是否添加偏置

二、实战演示

预定要的in_features为1,1,x形式

out_features为1,1,y的形式

1.将CIFAR10图片数据集进行线性变换

代码如下:

python 复制代码
import torch
import torchvision
from torch.utils.data import DataLoader

# 准备数据
test_set = torchvision.datasets.CIFAR10("dataset",
                                        train=False,
                                        transform=torchvision.transforms.ToTensor(),
                                        download=True)
# 加载数据集
dataloader = DataLoader(test_set,batch_size=64)

# 查看输入的通道数
# for data in dataloader:
#     imgs, target = data
#     print(imgs.shape)  # torch.Size([64, 3, 32, 32])
#     # 将img进行reshape成1,1,x的形式
#     input = torch.reshape(imgs,(1,1,1,-1)) # 每次一张图,1通道,1*自动计算x
#     print(input.shape) # torch.Size([1, 1, 1, 196608])

# 搭建神经网络,设置预定的输出特征值为10
class Lgl(torch.nn.Module):
    def __init__(self):
        super(Lgl, self).__init__()
        self.linear1 = torch.nn.Linear(196608,10)  # 输入数据的特征值196608,输出特征值10
    def forward(self, input):
        output = self.linear1(input)
        return output
# 实例化
l = Lgl()
# 进行线性操作

for data in dataloader:
    imgs, target = data
    print(imgs.shape)  # torch.Size([64, 3, 32, 32])
    # 将img进行reshape成1,1,x的形式
    input = torch.reshape(imgs,(1,1,1,-1)) # 每次一张图,1通道,1*自动计算x
    output = l(input)
    print(output.shape) # torch.Size([1, 1, 1, 10])
python 复制代码
原先的图片shape:torch.Size([64, 3, 32, 32])
reshape后的图片shape:torch.Size([1, 1, 1, 196608])
经过线性后的图片shape:torch.Size([1, 1, 1, 10])
原先的图片shape:torch.Size([64, 3, 32, 32])
reshape后的图片shape:torch.Size([1, 1, 1, 196608])
经过线性后的图片shape:torch.Size([1, 1, 1, 10])
......

除了使用reshape后,还可以使用torch.flatten()进行修改尺寸,将其自动修改为一维。
torch.flatten(input, start_dim=0, end_dim=- 1)
将输入tensor的第start_dim维到end_dim维之间的数据"拉平"成一维tensor

修改成flatten后代码如下

python 复制代码
import torch
import torchvision
from torch.utils.data import DataLoader

# 准备数据
test_set = torchvision.datasets.CIFAR10("dataset",
                                        train=False,
                                        transform=torchvision.transforms.ToTensor(),
                                        download=True)
# 加载数据集
dataloader = DataLoader(test_set,batch_size=64)

# 查看输入的通道数
# for data in dataloader:
#     imgs, target = data
#     print(imgs.shape)  # torch.Size([64, 3, 32, 32])
#     # 将img进行reshape成1,1,x的形式
#     input = torch.reshape(imgs,(1,1,1,-1)) # 每次一张图,1通道,1*自动计算x
#     print(input.shape) # torch.Size([1, 1, 1, 196608])

# 搭建神经网络,设置预定的输出特征值为10
class Lgl(torch.nn.Module):
    def __init__(self):
        super(Lgl, self).__init__()
        self.linear1 = torch.nn.Linear(196608,10)  # 输入数据的特征值196608,输出特征值10
    def forward(self, input):
        output = self.linear1(input)
        return output
# 实例化
l = Lgl()
# 进行线性操作

for data in dataloader:
    imgs, target = data
    print(f"原先的图片shape:{imgs.shape}")  # torch.Size([64, 3, 32, 32])
    # 将img进行reshape成1,1,x的形式
    input = torch.flatten(imgs) # 每次一张图,1通道,1*自动计算x
    print(f"flatten后的图片shape:{input.shape}")
    output = l(input)
    print(f"经过线性后的图片shape:{output.shape}") # torch.Size([1, 1, 1, 10])
python 复制代码
原先的图片shape:torch.Size([64, 3, 32, 32])
flatten后的图片shape:torch.Size([196608])
经过线性后的图片shape:torch.Size([10])
原先的图片shape:torch.Size([64, 3, 32, 32])
flatten后的图片shape:torch.Size([196608])
经过线性后的图片shape:torch.Size([10])
......
相关推荐
不可求~43 分钟前
用 AI 读论文别只看摘要:建立可追溯的证据链
人工智能·深度学习·机器学习
今天AI了吗1 小时前
Python 基础语法(一):常量、变量、输入输出与运算符
开发语言·数据库·人工智能·python·sql·深度学习·机器学习
CODER03046 小时前
Anaconda和Mamba创建环境管理包常用命令合集
python·深度学习·conda·虚拟环境·mamba·常用命令大全
俊基科技10 小时前
别自己写算法了,让这颗37.5毫米的模组替你“闭嘴干活”
神经网络·算法·硬件开发·ai降噪·语音模块·回音消除
高洁0113 小时前
智能体的“记忆”难题
python·深度学习·机器学习·transformer
小王20414 小时前
Day 21:卷积神经网络CNN — 深入理解卷积
人工智能·神经网络·cnn
程序猿零零漆14 小时前
PyTorch 入门核心:张量操作与自动微分全解析
人工智能·pytorch·python
十三画者1 天前
【文献分享】ConfRetro:融合3D构象信息的逆合成预测Transformer框架
人工智能·深度学习·数据挖掘·数据分析·transformer·数据可视化
别动我齐刘海1 天前
机器人运动控制学习2——基础进阶
c++·人工智能·神经网络·学习·目标检测·机器学习·机器人
雷帝木木1 天前
数据湖与数据仓库:从理论到实践
人工智能·python·深度学习·机器学习