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])
相关推荐
坤坤子吖几秒前
算法学习——高精度加减乘除
c++·笔记·学习·算法
国科安芯2 分钟前
星载通信载荷信号处理中抗辐射微控制器的选型与适应性分析
人工智能·嵌入式硬件·mcu·信号处理·risc-v·抗辐射·空间信息
小小张说故事4 分钟前
Python 中 __new__ 和 __init__ 到底谁才是构造函数?一文讲透区别与 5 个坑
后端·python
老A的AI实验室6 分钟前
赛博月刊 #2026年9月
大数据·人工智能·深度学习·ai·llm
FII工业富联科技服务10 分钟前
2026工业AI智能体架构全景:从单Agent到多Agent协同的工厂级闭环实践
人工智能·ai·机器人·制造
HY小宝F12 分钟前
树莓派智能摄像头系统 30 天重学计划之 Day 03 · 网络基础:建立“包“的思维 —— 学习总结
网络·学习
言乐612 分钟前
Python实现关税自动计算模型
开发语言·python·django·virtualenv·pygame
伞伞悦读13 分钟前
从零打通 Hermes Agent:Windows + WSL2 + Clash 全链路安装、认证与首次实战
python·语言模型
光依旧15 分钟前
MCP实战手记(八):从“能跑“到“能上线“——无状态MCP Server的生产落地清单
java·人工智能·spring boot·架构·ai agent·mcp
故七月19 分钟前
GEO 信源评估体系:如何判断一条网页信源能否被大模型采信
前端·网络·人工智能