首页 游戏 软件 资讯 排行榜 专题
首页
AI
【论文复现-图像分类】基于PaddlePaddle实现RAM

【论文复现-图像分类】基于PaddlePaddle实现RAM

热心网友
36
转载
2025-07-17
本文介绍Recurrent Attention Model (RAM)的复现情况。RAM通过循环神经网络处理图像子区域信息,自主选择子区域,降低复杂度。其含glimpse sensor等五部分结构。复现用MNIST数据集,验证误差1.18%(290epoch),测试误差1.17%~1.28%,还提及复现中rsample方法和索引操作的问题及解决,提升了训练速度。

【论文复现-图像分类】基于paddlepaddle实现ram - 游乐网

一、论文简介

1.1 简介

Recurrent Attention Model (RAM),它能顺序处理输入信息,在每个时间步关注图像内不同的子区域,然后增量式的结合来自这些固定位置的信息,并建立图像的动态内部表示。

免费影视、动漫、音乐、游戏、小说资源长期稳定更新! 👉 点此立即查看 👈

RAM的优点在于能自主选择图像的子区域进行处理,而不像传统的卷积模型一样复杂度随着输入图像像素变大而线性增长。【论文复现-图像分类】基于PaddlePaddle实现RAM - 游乐网

论文地址

1.2 网络结构

本文将注意力问题建模为目标导向的agent与视觉环境交互的序列决策过程,agent的核心是一个循环神经网络,它在每一时间步处理来自sensor收集的子图信息,并随着时间推移集成图像信息,并选择如何行动和部署下一个时间步的sensor。

【论文复现-图像分类】基于PaddlePaddle实现RAM - 游乐网

RAM模型结构如上图所示,其中包含如下五个部分:

glimpse sensor:glimpse sensor受到视网膜注意力机制的启发,即人往往能清晰的看见所关注对象的细节(内容少,高分辨率),同时保留对背景的模糊感受(内容多,低分辨率)。于是设计的glimpse sensor能从图像 x中提取漏斗状的一瞥(glimpse)phi,sensor首先编码靠近位置l的一块高像素的小区域,然后再渐进的从l附近取更大且像素更低的子区域(所有的截取的子区域需要缩放到同一大小,所以大图像素低),从而得到原始图像 x的压缩表示;

下面第一张图是截取位置l附近不同尺度的区域,然后第二章是将他们缩放到同一尺度,使得细节部分有高分辨率,背景低分辨率。

【论文复现-图像分类】基于PaddlePaddle实现RAM - 游乐网

【论文复现-图像分类】基于PaddlePaddle实现RAM - 游乐网

glimpse network: 该网络将sensor得到的压缩表示"what" (phi)和位置信息"where" (l)结合起来,得到这一瞥的特征向量g_t;

core network: 核心网络是个循环神经网络,该网络维持一个内部状态 h_t ,代表从过去观测历史中提取的整合信息。它通过状态向量 h_t 编码angent对环境的知识,并且在每个时间步 t都会更新。时间步t时的输入为上一个时刻glimpse向量g_(t-1)和状态向量h_(t-1);

location network:位置网络,使用rnn状态向量h_t,在时间步t时产生shape为[bsz,2]的位置坐标l_t,再同输入图像 x送入glimpse得到输入向量g_(t+1),同状态向量h_t作为t+1时刻rnn的输入;

action network: 在固定数的时间步之后,使用rnn的内部状态‘h_t’生成最终的分类输出 y。

总的来说,RAM是围绕rnn展开的,输入是glimpse向量和t时刻状态向量,输出是t+1时刻状态向量,代表集成的图像信息。利用状态向量输入两个子网络location和action 可以得到两个输出:l_t和a_t,l_t用于指导sensor截取子图并编码为输入向量,a_t用来完成分类任务。

二、复现结果

2.1 实验结果

本项目使用28x28的MNIST数据集来复现,RAM模型包含6个glimpses,patch_size为8x8,缩放因子scale为1,论文中指标为:

【论文复现-图像分类】基于PaddlePaddle实现RAM - 游乐网

本项目的验证误差为1.18%(290epoch),原文和本项目在MNIST测试集上的误差为:

本项目的模型权重ram_6_8x8_1_model_best.pdparams(aistudio上zip里面有)已经上传到百度网盘:链接 ,提取码:v6d3

2.2 实验环境以及超参

注:

第一次是先用factor=0.1,patience=20训练了200轮,发现142轮达到最优,未达到指定精度,且后面学习率过小为0了。于是从142轮开始恢复训练,初始学习率仍为3e-4,然后factor=0.8,patience=10, 继续训练到290轮,详细见logs里RAM_local290.log日志。且该指标是在本地3060环境达到精度,3060一轮约45s,v100一轮约30s。

第二次是在aistudio上,初始学习率3e-4,然后factor=0.8,patience=10,训练到200轮,发现第192轮best,test acc为1.68,然后恢复训练,到315轮时验证误差最小为1.033%,于是停止训练,评估得到1.28%

三、准备工作

In [1]
# 解压代码!unzip RAM.zip
登录后复制
Archive:  RAM.zipreplace RAM/align.py? [y]es, [n]o, [A]ll, [N]one, [r]ename: ^C
登录后复制In [ ]
# 进入目录,并安装依赖%cd RAM/!pip install tensorboard_logger
登录后复制
/home/aistudio/RAMLooking in indexes: https://pypi.tuna.tsinghua.edu.cn/simpleRequirement already satisfied: tensorboard_logger in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (0.1.0)Requirement already satisfied: six in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from tensorboard_logger) (1.15.0)Requirement already satisfied: scipy>=0.19.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from tensorboard_logger) (1.6.3)Requirement already satisfied: protobuf in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from tensorboard_logger) (3.14.0)Requirement already satisfied: numpy in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from tensorboard_logger) (1.20.3)Requirement already satisfied: pillow>=4.1.1 in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from tensorboard_logger) (7.1.2)
登录后复制

目录结构

.├── README.md├── align.py # 转换权重├── ckpt # 权重│   └── ram_6_8x8_1_model_best.pdparams├── config.py # 配置文件├── data # 数据│   ├── MNIST├── data_loader.py # 加载数据├── logs # 日志├── main.py # 主函数├── model.py # RAM主体模型├── modules.py # RAM5个部分├── plot_glimpses.py # 画图├── plots # 图片├── requirements.txt├── trainer.py # 训练、评估函数└── utils.py # 工具
登录后复制

四、模型训练

In [ ]
!python main.py
登录后复制
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/__init__.py:107: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  from collections import MutableMapping/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/rcsetup.py:20: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  from collections import Iterable, Mapping/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/colors.py:53: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  from collections import SizedW1123 12:01:46.425436   726 device_context.cc:447] Please NOTE: device: 0, GPU Compute Capability: 7.0, Driver API Version: 11.0, Runtime API Version: 10.1W1123 12:01:46.429379   726 device_context.cc:465] device: 0, cuDNN Version: 7.6.[*] Model Checkpoint Dir: ./ckpt[*] Param Path: ./ckpt/ram_6_8x8_1_params.json2024-11-23 12:01:49,497 | RAM: [*] Train on 54000 samples, validate on 6000 samplesINFO:RAM:[*] Train on 54000 samples, validate on 6000 samples2024-11-23 12:01:49,497 | RAM: Epoch: 1/200 - LR: 0.000300INFO:RAM:Epoch: 1/200 - LR: 0.000300  0%|                                                 | 0/54000 [00:00登录后复制

五、模型评估

In [ ]
## aistudio上训练的,315轮,验证误差1.033,测试误差1.28%!python main.py --is_train=False --best True --ckpt_dir ckpt_aistudio
登录后复制
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/__init__.py:107: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  from collections import MutableMapping/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/rcsetup.py:20: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  from collections import Iterable, Mapping/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/colors.py:53: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  from collections import SizedW1124 09:46:43.853452   793 device_context.cc:447] Please NOTE: device: 0, GPU Compute Capability: 7.0, Driver API Version: 10.1, Runtime API Version: 10.1W1124 09:46:43.857133   793 device_context.cc:465] device: 0, cuDNN Version: 7.6.2024-11-24 09:46:48,040 | RAM: [*] Loading model from ckpt_aistudioINFO:RAM:[*] Loading model from ckpt_aistudio2024-11-24 09:46:48,050 | RAM: [*] Loaded ram_6_8x8_1_model_best.pdparams checkpoint @ epoch 315 with best valid acc of 98.917INFO:RAM:[*] Loaded ram_6_8x8_1_model_best.pdparams checkpoint @ epoch 315 with best valid acc of 98.917/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/tensor/creation.py:130: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations  if data.dtype == np.object:2024-11-24 09:46:53,835 | RAM: [*] Test Acc: 9872.0/10000 (98.72% - 1.28%)INFO:RAM:[*] Test Acc: 9872.0/10000 (98.72% - 1.28%)
登录后复制In [ ]
## 本地3060训练的,见日志logs/RAM_local290.log,290轮,验证误差1.15,测试误差1.17%!python main.py --is_train=False --best True
登录后复制
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/__init__.py:107: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  from collections import MutableMapping/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/rcsetup.py:20: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  from collections import Iterable, Mapping/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/colors.py:53: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  from collections import SizedINFO:matplotlib.font_manager:font search path ['/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf', '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/afm', '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/pdfcorefonts']INFO:matplotlib.font_manager:generated new fontManagerCache file /home/aistudio/.cache/paddle/dataset/mnist/t10k-images-idx3-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/t10k-images-idx3-ubyte.gz Begin to downloaditem 403/403 [============================>.] - ETA: 0s - 389us/itDownload finishedCache file /home/aistudio/.cache/paddle/dataset/mnist/t10k-labels-idx1-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/t10k-labels-idx1-ubyte.gz Begin to downloaditem 2/2 [===========================>..] - ETA: 0s - 642us/itDownload finishedW1124 09:37:17.144690   311 device_context.cc:447] Please NOTE: device: 0, GPU Compute Capability: 7.0, Driver API Version: 10.1, Runtime API Version: 10.1W1124 09:37:17.149226   311 device_context.cc:465] device: 0, cuDNN Version: 7.6.2024-11-24 09:37:22,326 | RAM: [*] Loading model from ./ckptINFO:RAM:[*] Loading model from ./ckpt2024-11-24 09:37:22,336 | RAM: [*] Loaded ram_6_8x8_1_model_best.pdparams checkpoint @ epoch 290 with best valid acc of 98.917INFO:RAM:[*] Loaded ram_6_8x8_1_model_best.pdparams checkpoint @ epoch 290 with best valid acc of 98.917/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/tensor/creation.py:130: DeprecationWarning: `np.object` is a deprecated alias for the builtin `object`. To silence this warning, use `object` by itself. Doing this will not modify any behavior and is safe. Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations  if data.dtype == np.object:2024-11-24 09:37:28,007 | RAM: [*] Test Acc: 9883.0/10000 (98.83% - 1.17%)INFO:RAM:[*] Test Acc: 9883.0/10000 (98.83% - 1.17%)
登录后复制

六、总结

这里就说下复现遇到的小坑:

1.rsample(location网络): paddle.distribution.Normal,没有torch.distribution.Normal().rsample方法, 参考torch源码实现后,在对齐精度时发现不能完全对齐,该操作有随机性,差0.3%左右,不过影响不大;

    def rsample(loc, scale):      shape = loc.shape      normal_ = paddle.nn.initializer.Normal()      eps = paddle.empty(shape, dtype=loc.dtype)      normal_(eps)      return loc + eps * scale
登录后复制

2.索引:

在glimpse的retina的extract_patch方法内,根据输入的位置信息lt[bsz,2],对图片进行采样(8*8patch)。

    def extract_patch(self, x, l, size):...        patch = []        for i in range(B):            subset=x[i, :, start[i, 1] : end[i, 1], start[i, 0] : end[i, 0]]            patch.append(subset)        return paddle.to_tensor(np.stack(patch))
登录后复制我在改完代码后发现paddle的训练速度250steps/s,而torch为900steps/s (本地3060)

【论文复现-图像分类】基于PaddlePaddle实现RAM - 游乐网

【论文复现-图像分类】基于PaddlePaddle实现RAM - 游乐网

然后逐个模块定位,最后发现glimpse里面这个采样的操作特别慢,128的bsz,for循环对每张图片切片得到8*8的patch,paddle需要0.07,torch需要0.003s左右,差了二三十倍,整体训练差了四五倍。【论文复现-图像分类】基于PaddlePaddle实现RAM - 游乐网

【论文复现-图像分类】基于PaddlePaddle实现RAM - 游乐网

我先试试基础api,select_index能对所有的图片截取相同的某几行或几列,不能达到取不同块的目的。考虑到索引操作都不需要梯度了,试了下numpy,发现速度较快,128bsz,迭代10次,共1280次索引,对比如下:最后改完后paddle速度达到1200,比参考代码快了1.33倍(aistudio上1800steps/s):

【论文复现-图像分类】基于PaddlePaddle实现RAM - 游乐网

总之,在遇到精度、速度差距大时,从上到下一层层慢慢debug就行啦~

来源:https://www.php.cn/faq/1412467.html
免责声明: 游乐网为非赢利性网站,所展示的游戏/软件/文章内容均来自于互联网或第三方用户上传分享,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系youleyoucom@outlook.com。

相关攻略

Pywinrm,一个 Python 管理利器!
科技数码
Pywinrm,一个 Python 管理利器!

Pywinrm 通过Windows远程管理(WinRM)协议,让Python能够像操作本地一样执行远程Windows命令,真正打通了跨平台管理的最后一公里。 在混合IT环境中,Linux机器管理Wi

热心网友
04.07
全网炸了!5亿人用的Axios竟被投毒,你的密钥还保得住吗?
科技数码
全网炸了!5亿人用的Axios竟被投毒,你的密钥还保得住吗?

早些时候,聊过 Python 领域那场惊心动魄的供应链攻击。当时我就感叹,虽然我们 JavaScript 开发者对这类套路烂熟于心,但亲眼目睹这种规模的“投毒”还是头一次。 早些时候,聊过 Pyth

热心网友
04.07
Toga,一个超精简的 Python 项目!
科技数码
Toga,一个超精简的 Python 项目!

Toga 是 BeeWare 家族的核心成员,号称“写一次,跑遍所有平台”,而且用的是系统原生控件,不是那种一看就是网页套壳的界面 。 写了这么多年 Python,你是不是也想过:要是能一套代码跑

热心网友
04.07
Python 异常处理:别再用裸奔的 try 了
科技数码
Python 异常处理:别再用裸奔的 try 了

异常处理的核心:让错误在正确的地方被有效处理。正确的地方,就是别在底层就把异常吞了,也别在顶层还抛裸奔的 Exception。 异常处理写得好,半夜不用起来改 bug。1 你是不是也这么干过?tr

热心网友
04.07
OpenClaw如何自定义SKILL
AI
OpenClaw如何自定义SKILL

1 Skills机制概述 提起OpenClaw的Skills机制,不少人可能会把它想象成传统意义上的可执行插件。其实,它的内涵要更精妙一些。 简单说,Skills本质上是一套基于提示驱动的能力扩展机制。它并不是一个可以独立“跑”起来的程序模块,而是通过一份结构化描述文件(核心就是那个SKILL m

热心网友
04.07

最新APP

宝宝过生日
宝宝过生日
应用辅助 04-07
台球世界
台球世界
体育竞技 04-07
解绳子
解绳子
休闲益智 04-07
骑兵冲突
骑兵冲突
棋牌策略 04-07
三国真龙传
三国真龙传
角色扮演 04-07

热门推荐

美国SEC主席Paul Atkins证实:加密货币安全港提案已送交白宫审查
web3.0
美国SEC主席Paul Atkins证实:加密货币安全港提案已送交白宫审查

加密货币行业翘首以盼的监管里程碑,终于有了实质性进展。美国证券交易委员会(SEC)主席保罗·阿特金斯(Paul Atkins)近日证实,那份允许加密项目在早期获得注册豁免权的“安全港”框架提案,已经正式送抵白宫,进入了最终审查阶段。 在范德堡大学与区块链协会联合举办的数字资产峰会上,阿特金斯透露了这

热心网友
04.08
微策略Strategy报告:第一季录得144.6亿美元浮亏 再斥资约3.3亿美元买进4871枚比特币
web3.0
微策略Strategy报告:第一季录得144.6亿美元浮亏 再斥资约3.3亿美元买进4871枚比特币

微策略Strategy报告:第一季录得144 6亿美元浮亏 再斥资约3 3亿美元买进4871枚比特币 市场震荡的威力有多大?看看Strategy的最新季报就明白了。根据其最新向美国证管会(SEC)提交的8-K报告,受市场剧烈波动影响,这家公司所持的比特币在第一季度录得了一笔惊人的数字——144 6亿

热心网友
04.08
稳定币发行商Tether再扩Web3版图!Paolo Ardoino:正开发去中心化搜索引擎Hypersearch
web3.0
稳定币发行商Tether再扩Web3版图!Paolo Ardoino:正开发去中心化搜索引擎Hypersearch

稳定币巨头Tether的动向,向来是加密世界的风向标。这不,它向Web3基础设施的版图扩张,又迈出了关键一步。公司执行长Paolo Ardoino在社交平台X上透露,其工程团队正在全力“烹制”一个新项目——去中心化搜索引擎 “Hypersearch”。这个消息一出,立刻引发了行业的广泛猜想。 采用D

热心网友
04.08
Base链首个原生DeFi借贷协议Seamless Protocol倒闭 将于2026年6月30日下线
web3.0
Base链首个原生DeFi借贷协议Seamless Protocol倒闭 将于2026年6月30日下线

基地位于Coinbase旗下以太坊Layer2网络Base的Seamless Protocol,日前正式宣告了服务的终结。这个曾经吸引了超过20万用户的原生DeFi借贷协议,在运营不到三年后,终究没能跑赢时间。它主打的核心产品是Integrated Leverage Markets(ILMs)——一

热心网友
04.08
PAAL代币如何参与治理?社区投票能决定哪些事项?
web3.0
PAAL代币如何参与治理?社区投票能决定哪些事项?

PAAL代币揭秘:深度解析Web3社区治理的核心钥匙 在去中心化自治组织的浪潮中,谁真正掌握了项目的话语权?PAAL代币提供了一套系统化的答案。它不仅是生态内流转的价值媒介,更是开启链上治理大门的核心凭证。通过持有并质押PAAL代币,用户能够对协议升级、资金分配乃至战略方向等关键事务投出决定性的一票

热心网友
04.08