各种注意力机制,MLP,Re-Parameter系列的PyTorch实现

PyTorch注意力机制 文章目录 1.注意力机制 1.1 注意力机制 1.1.1 非参注意力池化层 1.1.2 Nadaraya-Watson核回归 1.1.3 参数化的注意力机制 1.1.4 注意力汇聚:Nadaraya-Watson核回归的代码实现 2 注意力分数 2.1 加性注意力 2.2 缩放点积注意力 2.3 注意力打分函数代码实现 3 使用注意力机制的seq2seq 4 多头注意力 5 自注意力 5.1 比较卷积神经网络、循环神经网络和自注意力 5.2 位置编码 5.2.1 绝对位置信 阅读详情

作者|xmu-xiaoma666

来自|AI公园   编译|onghuaiyang

导读

给出了整个系列的PyTorch的代码实现,以及使用方法。

各种注意力机制

  • Pytorch implementation of "Beyond Self-attention: External Attention using Two Linear Layers for Visual Tasks---arXiv 2020.05.05"

  • Pytorch implementation of "Attention Is All You Need---NIPS2017"

  • Pytorch implementation of "Squeeze-and-Excitation Networks---CVPR2018"

  • Pytorch implementation of "Selective Kernel Networks---CVPR2019"

  • Pytorch implementation of "CBAM: Convolutional Block Attention Module---ECCV2018"

  • Pytorch implementation of "BAM: Bottleneck Attention Module---BMCV2018"

  • Pytorch implementation of "ECA-Net: Efficient Channel Attention for Deep Convolutional Neural Networks---CVPR2020"

  • Pytorch implementation of "Dual Attention Network for Scene Segmentation---CVPR2019"

  • Pytorch implementation of "EPSANet: An Efficient Pyramid Split Attention Block on Convolutional Neural Network---arXiv 2020.05.30"

  • Pytorch implementation of "ResT: An Efficient Transformer for Visual Recognition---arXiv 2020.05.28"

1. 外部注意力

1.1. 论文

"Beyond Self-attention: External Attention using Two Linear Layers for Visual Tasks"

1.2. 概要

1.3. 代码
from attention.ExternalAttention import ExternalAttention
import torch

input=torch.randn(50,49,512)
ea = ExternalAttention(d_model=512,S=8)
output=ea(input)
print(output.shape)

2. 自注意力

2.1. 论文

"Attention Is All You Need"

1.2. 概要

1.3. 代码
from attention.SelfAttention import ScaledDotProductAttention
import torch

input=torch.randn(50,49,512)
sa = ScaledDotProductAttention(d_model=512, d_k=512, d_v=512, h=8)
output=sa(input,input,input)
print(output.shape)

3. 简化的自注意力

3.1. 论文

None

3.2. 概要

3.3. 代码
from attention.SimplifiedSelfAttention import SimplifiedScaledDotProductAttention
import torch

input=torch.randn(50,49,512)
ssa = SimplifiedScaledDotProductAttention(d_model=512, h=8)
output=ssa(input,input,input)
print(output.shape)


4. Squeeze-and-Excitation 注意力

4.1. 论文

"Squeeze-and-Excitation Networks"

4.2. 概要

4.3. 代码
from attention.SEAttention import SEAttention
import torch

input=torch.randn(50,512,7,7)
se = SEAttention(channel=512,reduction=8)
output=se(input)
print(output.shape)


5. SK 注意力

5.1. 论文

"Selective Kernel Networks"

5.2. 概要

5.3. 代码
from attention.SKAttention import SKAttention
import torch

input=torch.randn(50,512,7,7)
se = SKAttention(channel=512,reduction=8)
output=se(input)
print(output.shape)

6. CBAM 注意力

6.1. 论文

"CBAM: Convolutional Block Attention Module"

6.2. 概要

6.3. 代码
from attention.CBAM import CBAMBlock
import torch

input=torch.randn(50,512,7,7)
kernel_size=input.shape[2]
cbam = CBAMBlock(channel=512,reduction=16,kernel_size=kernel_size)
output=cbam(input)
print(output.shape)



7. BAM 注意力

7.1. 论文

"BAM: Bottleneck Attention Module"

7.2. 概要

7.3. 代码
from attention.BAM import BAMBlock
import torch

input=torch.randn(50,512,7,7)
bam = BAMBlock(channel=512,reduction=16,dia_val=2)
output=bam(input)
print(output.shape)



8. ECA 注意力

8.1. 论文

"ECA-Net: Efficient Channel Attention for Deep Convolutional Neural Networks"

8.2. 概要

8.3. Code
from attention.ECAAttention import ECAAttention
import torch

input=torch.randn(50,512,7,7)
eca = ECAAttention(kernel_size=3)
output=eca(input)
print(output.shape)


9. DANet 注意力

9.1. 论文

"Dual Attention Network for Scene Segmentation"

9.2. 概要

9.3. 代码
from attention.DANet import DAModule
import torch

if __name__ == '__main__':
    input=torch.randn(50,512,7,7)
    danet=DAModule(d_model=512,kernel_size=3,H=7,W=7)
    print(danet(input).shape)


10. 金字塔拆分注意力

10.1. 论文

"EPSANet: An Efficient Pyramid Split Attention Block on Convolutional Neural Network"

10.2. 概要

10.3. 代码
from attention.PSA import PSA
import torch

if __name__ == '__main__':
    input=torch.randn(50,512,7,7)
    psa = PSA(channel=512,reduction=8)
    output=psa(input)
    print(output.shape)



11. 高效多头自注意力

11.1. 论文

"ResT: An Efficient Transformer for Visual Recognition"

11.2. 概要

11.3. 代码
from attention.EMSA import EMSA
import torch
from torch import nn
from torch.nn import functional as F

if __name__ == '__main__':
    input=torch.randn(50,64,512)
    emsa = EMSA(d_model=512, d_k=512, d_v=512, h=8,H=8,W=8,ratio=2,apply_transform=True)
    output=emsa(input,input,input)
    print(output.shape)
    

MLP 系列

  • Pytorch implementation of "RepMLP: Re-parameterizing Convolutions into Fully-connected Layers for Image Recognition---arXiv 2020.05.05"

  • Pytorch implementation of "MLP-Mixer: An all-MLP Architecture for Vision---arXiv 2020.05.17"

  • Pytorch implementation of "ResMLP: Feedforward networks for image classification with data-efficient training---arXiv 2020.05.07"

  • Pytorch implementation of "Pay Attention to MLPs---arXiv 2020.05.17"

1. RepMLP

1.1. 论文

"RepMLP: Re-parameterizing Convolutions into Fully-connected Layers for Image Recognition"

1.2. 概要

1.3. 代码
from mlp.repmlp import RepMLP
import torch
from torch import nn

N=4 #batch size
C=512 #input dim
O=1024 #output dim
H=14 #image height
W=14 #image width
h=7 #patch height
w=7 #patch width
fc1_fc2_reduction=1 #reduction ratio
fc3_groups=8 # groups
repconv_kernels=[1,3,5,7] #kernel list
repmlp=RepMLP(C,O,H,W,h,w,fc1_fc2_reduction,fc3_groups,repconv_kernels=repconv_kernels)
x=torch.randn(N,C,H,W)
repmlp.eval()
for module in repmlp.modules():
    if isinstance(module, nn.BatchNorm2d) or isinstance(module, nn.BatchNorm1d):
        nn.init.uniform_(module.running_mean, 0, 0.1)
        nn.init.uniform_(module.running_var, 0, 0.1)
        nn.init.uniform_(module.weight, 0, 0.1)
        nn.init.uniform_(module.bias, 0, 0.1)

#training result
out=repmlp(x)
#inference result
repmlp.switch_to_deploy()
deployout = repmlp(x)

print(((deployout-out)**2).sum())

2. MLP-Mixer

2.1. 论文

"MLP-Mixer: An all-MLP Architecture for Vision"

2.2. 概要

2.3. 代码

from mlp.mlp_mixer import MlpMixer
import torch
mlp_mixer=MlpMixer(num_classes=1000,num_blocks=10,patch_size=10,tokens_hidden_dim=32,channels_hidden_dim=1024,tokens_mlp_dim=16,channels_mlp_dim=1024)
input=torch.randn(50,3,40,40)
output=mlp_mixer(input)
print(output.shape)


3. ResMLP

3.1. 论文

"ResMLP: Feedforward networks for image classification with data-efficient training"

3.2. 概要

3.3. 代码
from mlp.resmlp import ResMLP
import torch

input=torch.randn(50,3,14,14)
resmlp=ResMLP(dim=128,image_size=14,patch_size=7,class_num=1000)
out=resmlp(input)
print(out.shape) #the last dimention is class_num


4. gMLP

4.1. 论文

"Pay Attention to MLPs"

4.2. 概要

4.3. 代码
from mlp.g_mlp import gMLP
import torch

num_tokens=10000
bs=50
len_sen=49
num_layers=6
input=torch.randint(num_tokens,(bs,len_sen)) #bs,len_sen
gmlp = gMLP(num_tokens=num_tokens,len_sen=len_sen,dim=512,d_ff=1024)
output=gmlp(input)
print(output.shape)

Re-Parameter 系列

  • Pytorch implementation of "RepVGG: Making VGG-style ConvNets Great Again---CVPR2021"

  • Pytorch implementation of "ACNet: Strengthening the Kernel Skeletons for Powerful CNN via Asymmetric Convolution Blocks---ICCV2019"

1. RepVGG

1.1. 论文

"RepVGG: Making VGG-style ConvNets Great Again"

1.2. 概要

1.3. 代码
from rep.repvgg import RepBlock
import torch


input=torch.randn(50,512,49,49)
repblock=RepBlock(512,512)
repblock.eval()
out=repblock(input)
repblock._switch_to_deploy()
out2=repblock(input)
print('difference between vgg and repvgg')
print(((out2-out)**2).sum())

2. ACNet

2.1. 论文

"ACNet: Strengthening the Kernel Skeletons for Powerful CNN via Asymmetric Convolution Blocks"

2.2. 概要

2.3. 代码
from rep.acnet import ACNet
import torch
from torch import nn

input=torch.randn(50,512,49,49)
acnet=ACNet(512,512)
acnet.eval()
out=acnet(input)
acnet._switch_to_deploy()
out2=acnet(input)
print('difference:')
print(((out2-out)**2).sum())


英文原文:https://github.com/xmu-xiaoma666/External-Attention-pytorch

PyTorch——自注意力(self-attention)机制实现(代码详解) 参考链接 https://www.bilibili.com/video/BV1JE411g7XF?p=54 https://arxiv.org/abs/1706.03762 https://blog.youkuaiyun.com/qq_36653505/article/details/83375160 简述自注意力机制(self-attention) self-attention可以视为一个特征提取层,给定输入特征a1,a2,⋅⋅⋅ana^{1},a^{2},\cdot \cdot \cdot a^{n}a1,a2 阅读详情

相关推荐

注意力机制讲解与代码解析

面试考的所有注意力机制代码与解析

slamer111的博客 5500

注意力机制之Efficient Multi-Head Self-Attention

它的主要输入是查询、键和值,其中每个输入都是一个三维张量(batch_size,sequence_length,hidden_size),其中hidden_size是嵌入维度。(2)每个head只有q,k,v的部分信息,如果q,k,v的维度太小,那么就会导致获取不到连续的信息,从而导致性能损失。这篇文章给出的思路也非常简单,在SA中,在FC之前,用了一个卷积来降低了空间的维度,从而得到空间维度上更小的K和V。在此文件的示例中,EMSA模块的内部参数已经初始化,可以将数据传递给模块实例,并检查输出形状。

qq_38915354的博客 3318

Unlimiformer:突破Transformer长文本瓶颈的三层架构解析

Transformer的自注意力机制因O(L²)计算复杂度,天然难以处理万字级以上真实长文档。其本质限制在于全局KV缓存不可扩展,而非参数量或训练策略问题。Unlimiformer提出一种工程友好、可微分、可追溯的长上下文增强范式,通过Retriever(轻量检索)、Compressor(可学习池化)与Re-ranker(动态重排序)三层协同,在不改变基座模型结构的前提下,实现128K级上下文支持。该方案兼顾精度、显存效率与原文可解释性,特别适用于法律合同分析、医学文献综述、超长代码理解等需跨段落推理且要求

tyygming的专栏 378

pytorch注意力机制

最近看了一篇大佬的注意力机制的文章然后自己花了一上午的时间把按照大佬的图把大佬提到的注意力机制都复现了一遍,大佬有一些写的复杂的网络我按照自己的理解写了几个简单的版本接下来就放出我写的代码。顺便从大佬手里盗走一些图片,等我有时间一起进行替换,在此特别鸣谢这位大佬。

一个学长的博客 4022

GCViT图像分类实战:局部卷积与全局注意力协同建模

Vision Transformer(ViT)作为现代视觉主干,面临局部细节建模弱与全局语义感知割裂的固有矛盾;GCViT通过Local-Global-Local(LGL)块设计,在统一token空间内融合深度卷积的归纳偏置与自注意力的长程建模能力,其核心Global Context Token(GCT)模块以轻量方式注入图像级语义先验,显著提升模型对长尾分布、遮挡干扰及多尺度变化的鲁棒性。该架构在森林图像分类等典型细粒度视觉任务中验证了工程落地价值——兼顾精度、显存效率与推理稳定性,适用于遥感解译、生物多

ciya3282的博客 361

IBTrACS v04r01 数据提取实战:Pandas 筛选 JTWC/CMA/JMA 3机构最佳路径数据

本文详细介绍了如何使用 Pandas 高效提取和处理 IBTrACS v04r01 数据集中的最佳路径数据,特别针对 JTWC、CMA 和 JMA 三家权威机构的数据进行对比分析。通过构建可复用的数据提取函数,解决多机构数据质量差异问题,并提供高级分析与可视化应用示例,助力热带气旋研究。

clijovtbq401783153的博客 517

朴实无华!各种注意力机制,MLP,Re-Parameter系列的PyTorch实现代码总结!

作者:xmu-xiaoma666编译:ronghuaiyang转自:AI公园导读给出了整个系列的PyTorch的代码实现,以及使用方法。各种注意力机制Pytorch implementat...

AI蜗牛车 1687

芯片详解——AD7606

AD7606详解

weixin_45661757的博客 5023

探索现代注意力机制与MLP架构的技术演进与设计范式

在深度学习模型架构的演进历程中,注意力机制和多层感知机(MLP)经历了从边缘到核心的转变。External-Attention-pytorch项目集中展示了这一技术演进的最新成果,为研究者提供了从理论到实践的完整实现参考。本文将从技术挑战、架构演进和实现范式三个维度,深入分析注意力机制与MLP在现代视觉模型中的设计哲学与技术实现。 ## 注意力机制的核心挑战与设计权衡 传统卷积神经网络在长期依

gitblog_00957的博客 962

手把手教你用OpenCompass评估Qwen1.5-1.8B模型(含数据集配置详解)

本文提供了使用OpenCompass评估Qwen1.5-1.8B-Chat模型的详细实战教程。内容涵盖从创建独立Python环境、下载模型与核心数据集,到编写配置文件、执行评测命令及解读结果的完整流程。重点解析了模型与数据集的配置细节,并分享了性能调优与常见问题排查方法,旨在帮助开发者快速上手系统化的模型评估。

weixin_29228781的博客 139

【OpenSearch】从零到一:手把手搭建OpenSearch与Dashboard可视化平台

本文提供了一份详细的OpenSearch与Dashboard可视化平台从零搭建指南。内容涵盖环境准备、系统调优、核心服务安装配置、Dashboard部署与汉化,以及生产环境安全加固建议,帮助用户快速构建一个功能完整的搜索与分析平台。

devops8pract的博客 617

深度解析External-Attention-pytorch:现代注意力机制的PyTorch实现宝库

**External-Attention-pytorch** 是一个全面而强大的深度学习库,专注于实现各种现代注意力机制、骨干网络、MLP架构、重参数化技术和卷积操作。这个项目为研究人员和开发者提供了一个统一的平台,用于探索、比较和集成最新的注意力机制研究成果,特别在计算机视觉和自然语言处理领域具有重要价值。 ## 技术定位:从传统CNN到现代注意力机制的演进之路 在深度学习的发展历程中,注意

gitblog_00422的博客 763

WinForm制作文件传输助手,Tcp局域网传输文件,传输速度受限于宽带和硬盘速度上限

文件传输助手为什么会出现,是因为项目上有些特殊的地方限制太多了,连插硬盘都需要关软件,联网又要开很不方便,网络限制一般软件只能局域网通信,还要开特定的端口等,你才能在电脑上通信,这样和机房的服务器远程的时候文件就不好拿过去,又不可能每次都去开机房的门。现在这个功能比较简单,只能单文件发送,但是其实比U盘硬盘方便,一般的六类网线传输压缩包在50M/s以上,U盘硬盘复制就不行了,特别如果是像我们学校这种网络结构,一个学校都在一个局域网,那真的方便!普通的局域网用特定IP和端口,通信也是很方便的。

m0_69233031的博客 1672

注意力机制在脑机接口中的突破性应用:External-Attention-pytorch技术深度解析

脑机接口技术正面临前所未有的技术挑战:高维神经信号的特征提取、时序依赖性的精准建模、以及计算效率与模型性能的平衡。External-Attention-pytorch项目通过提供丰富的注意力机制实现,为这些挑战提供了创新性的解决方案。本文将从技术原理、架构创新、实践应用三个层面,深度解析这一工具库在神经信号解码中的突破性价值。 ## 神经信号解码的核心挑战与注意力机制的应对策略 神经信号解码的

gitblog_01007的博客 362

29、固态变压器拓扑、设计及其应用深度解析

本文深入解析了固态变压器(SST)的拓扑结构、设计方法及其在智能电网和能源互联网中的应用。重点探讨了机器学习在SST优化设计中的应用,包括中高频变压器设计、整体系统优化与建模研究。文章详细介绍了多端口SST的拓扑特点、功率传输机制及其作为能源路由器的关键作用,分析了不同端口数量下的控制复杂度与应用场景,并通过案例研究展示了四端口SST在分布式能源系统中的实际应用。最后,文章总结了多端口SST面临的技术挑战,并展望了未来在先进控制策略、集成化设计和标准化方面的发展方向。

study的专栏 3798

第16课:动手实战中文句法依存分析

句法分析是自然语言处理(NLP)中的关键技术之一,其基本任务是确定句子的句法结构或者句子中词汇之间的依存关系。主要包括两方面的内容:一是确定语言的语法体系,即对语言中合法句子的语法结构给予形式化的定义;另一方面是句法分析技术,即根据给定的语法体系,自动推导出句子的句法结构,分析句子所包含的句法单位和这些句法单位之间的关系。 句法分析被用在很多场景中,比如搜索引擎用户日志分析和关键词识别,比如信息抽...

春华秋实 2438

实战指南:使用External-Attention-pytorch构建高效的深度学习模型

External-Attention-pytorch是一个强大的PyTorch实现库,集成了多种**注意力机制**、MLP、重参数化和卷积操作,为深度学习研究者和工程师提供了丰富的模型组件。无论你是正在探索**注意力机制**的创新应用,还是需要快速构建高效的视觉模型,这个库都能为你提供即插即用的解决方案。 ## 核心优势:为什么选择External-Attention-pytorch Exte

gitblog_01026的博客 1124

对称式目镜设计实例

对称式目镜设计实例

weixin_72050316的博客 1163

深度学习工具库如何重塑高效模型构建?External-Attention-pytorch实战指南

在当今深度学习研究领域,如何快速构建高效模型已成为研究人员和工程师面临的核心挑战。传统方法往往需要从零开始实现复杂的注意力机制、MLP结构和卷积操作,这不仅耗时耗力,还容易引入错误。External-Attention-pytorch这一深度学习工具库通过集成40多种现代注意力机制和模型组件,为高效模型构建提供了革命性的解决方案。 ## 🎯 问题导向:传统模型开发的三大痛点 ### 1. 重

gitblog_01035的博客 449

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

从零手写GPT-2:PyTorch原生实现Transformer前向传播

Transformer是现代大语言模型的基石架构,其核心在于自注意力机制、层归一化、残差连接与前馈网络的协同运作。理解其原理不能止步于调用封装接口,而需深入张量流动与维度变换的本质。本文聚焦GPT-2这一经典解码器模型,以PyTorch原生模块逐层构建词嵌入、可学习位置编码、因果自注意力(含手动下三角掩码)、Pre-LN结构及GELU激活MLP,完整复现前向传播链路。过程强调形状一致性、权重绑定、广播机制与调试可观测性,为后续微调、长上下文扩展或LoRA适配等工程实践奠定结构直觉与代码掌控力。

Ha12312的博客 478

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

一键精准定位方法定义:PHP Companion 作用域跳转 goto_definition_scope 完整指南

PHP Companion 是一款面向 PHP 5.3+ 的 Sublime Text 插件,其 `goto_definition_scope` 命令能在调用成员方法时,让光标从 `$this->` 或 `self::` 直接精准跳转到**当前文件内**的方法定义;若无匹配,则自动回退到 Sublime Text 内置的 goto_definition 全局搜索,定位不再"跳错地方"。 ## ?

gitblog_01191的博客 865

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

Vision Transformer原理与PyTorch实战指南

Transformer架构通过自注意力机制(Self-Attention)实现了对序列数据的全局建模,这种机制最初在自然语言处理领域取得突破。在计算机视觉中,Vision Transformer(ViT)创新性地将Transformer应用于图像处理,通过图像分块嵌入(Patch Embedding)将2D图像转换为1D序列,配合位置编码保留空间信息。相比传统CNN,ViT能直接捕获长距离依赖关系,具有更好的可扩展性和并行计算效率。PyTorch框架为ViT实现提供了灵活的支持,包括多头注意力模块和Tran

weixin_30268071的博客 480

RTDETR改进专栏(包含RTDETR、YOLOV5-DETR、YOLOV8-DETR)

RTDETR改进专栏(性价比高,创新度高),目前RTDETR改进已经有350+个改进点!

qq_37706472的博客 7万+

软物理信息神经网络在传热问题中的工程实践

物理信息神经网络(PINN)作为融合深度学习与物理方程的新型计算方法,通过将控制方程嵌入神经网络损失函数,实现了对复杂物理系统的数据-机理联合建模。其核心原理是利用自动微分技术计算偏微分方程中的导数项,避免了传统数值方法对网格划分的依赖。在计算流体力学和传热学领域,这种方法特别适用于参数化研究和快速原型开发。针对传统PINN在强对流条件下训练不稳定的问题,软物理信息神经网络(Soft PINN)引入自适应加权和梯度松弛技术,显著提升了在平板对流传热等典型场景中的收敛性和精度。基于PyTorch的实现展示了从

weixin_34396103的博客 325
上一篇: 详细 | 图神经网络从入门到入门
下一篇: 中国Nature第一人,居然是清朝的他
机器学习算法那些事
博客等级 码龄9年 1633粉丝 62原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值