Pytorch个人学习记录总结 07

目录

神经网络-非线性激活

神经网络-线形层及其他层介绍


神经网络-非线性激活

官方文档地址:torch.nn --- PyTorch 2.0 documentation

常用的:Sigmoid、ReLU、LeakyReLU等。

作用:为模型引入非线性特征,这样才能在训练过程中训练出符合更多特征的模型。

其中有个参数是inplace,默认为False,表示是否就地改变输入值 ,True则表示直接改变了input不再有另外的返回值;False则没有直接改变input并有返回值(建议是inplace=False)。

python 复制代码
import torch
from torch import nn

input = torch.tensor([[3, -1],
                      [-0.5, 1]])
input = torch.reshape(input, (1, 1, 2, 2))

relu = nn.ReLU()
input_relu = relu(input)

print('input={}\ninput_relu:{}'.format(input, input_relu))

# input=tensor([[[[ 3.0000, -1.0000],
#           [-0.5000,  1.0000]]]])
# input_relu:tensor([[[[3., 0.],
#           [0., 1.]]]])

神经网络-线形层及其他层介绍

Linear Layers中的torch.nn.Linear(in_features, out_features, bias=True)。默认bias=True。对传入数据应用线性变换

Parameters:

  • in_features -- size of each input sample(每个输入样本的大小)
  • out_features -- size of each output sample(每个输出样本的大小)
  • bias -- If set to False, the layer will not learn an additive bias. Default: True(如果为False,则该层不会学习加法偏置,默认为true)

Shape :分别关注输入、输出的最后一个维度 的大小,在训练过程中,nn.Linear往往是当作的展平为一维后最后几步的全连接层,所以此时就只关注了通道数,即往往Input和Outputs是一维的)

"展平为一维"经常用到torch.nn.Flatten(start_dim=1, end_dim=- 1)

想说一下start_dim,它表示"从start_dim开始把后面的维度都展平到同一维度上",默认是是1,在实际训练中从start_dim=1开始展平,因为在训练中的tensor是4维的,分别是batch_size, C, H, W,而第0维的batch_size不能动它,所以是从1开始的。

还比较重要的有:torch.nn.BatchNorm2d、torch.nn.Dropout、Loss Functions(之后再讲)。其它的Transformer Layers、Recurrent Layers都不是很常用。

python 复制代码
import torch

# 对4维tensor展平,start_dim=1

input = torch.arange(54)
input = torch.reshape(input, (2, 3, 3, 3))

y_0 = torch.flatten(input)
y_1 = torch.flatten(input, start_dim=1)

print(input.shape)
print(y_0.shape)
print(y_1.shape)

# torch.Size([2, 3, 3, 3])
# torch.Size([54])
# torch.Size([2, 27])
相关推荐
风巽·剑染春水2 分钟前
【扩散模型原理】(六)A Unified and Systematic Lens on Diffusion Models(1)
人工智能·生成模型·diffusion·扩散模型
鱼宵5 分钟前
Spring AI 生产化改造:记忆落 Redis、向量落 ES,重启再也不丢
人工智能·redis·spring·elasticsearch·springai
小鹿的周先生5 分钟前
第18章-MCP
服务器·网络·人工智能
ab1237689 分钟前
OpenCV 学习笔记
笔记·opencv·学习
万物智能信息科技9 分钟前
温湿度传感器驱动开发—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
人工智能·驱动开发·华为·开源·harmonyos·鸿蒙
饼饼学习空间智能11 分钟前
低空经济进入新兴支柱产业:物理AI如何重构低空智能监管系统?
大数据·深度学习·机器学习
小静AI工程实验室11 分钟前
Python 爬虫解析 JSON-LD:多块 script、@graph 与坏数据的 9 个边界
爬虫·python·json
进击的横打14 分钟前
【人工智能】沙箱AI Agent 的安全隔离屏障
人工智能·安全
jason.zeng@150220722 分钟前
(八)现有架构上新增一个通用Excel导出工具
python·架构·langchain·excel·llama
袁袁袁袁满23 分钟前
AI Agent 如何“看懂“互联网?
爬虫·python·自动化·爬虫实战·多线程爬虫