政安晨:【Keras机器学习示例演绎】(三十二)—— 在 Vision Transformers 中学习标记化

news2025/2/23 20:04:31

目录

导言

导入

超参数

加载并准备 CIFAR-10 数据集

数据扩增

位置嵌入模块

变压器的 MLP 模块

令牌学习器模块

变换器组

带有 TokenLearner 模块的 ViT 模型

培训实用程序

使用 TokenLearner 培训和评估 ViT

实验结果

参数数量

最终说明


政安晨的个人主页政安晨

欢迎 👍点赞✍评论⭐收藏

收录专栏: TensorFlow与Keras机器学习实战

希望政安晨的博客能够对您有所裨益,如有不足之处,欢迎在评论区提出指正!

本文目标:为 "视觉变换器 "自适应生成较少数量的令牌。

导言


视觉变换器(Dosovitskiy 等人)和许多其他基于变换器的架构(Liu 等人、Yuan 等人)在图像识别方面取得了显著成果。

下面将简要介绍用于图像分类的视觉变换器架构所涉及的组件:

—— 从输入图像中提取小块图像。
—— 线性投影这些斑块。
—— 为这些线性投影添加位置嵌入。
—— 通过一系列 Transformer(Vaswani 等人)模块运行这些投影。
—— 最后,从最后的 Transformer 模块中提取表示并添加分类头。

如果我们获取 224x224 的图像并提取 16x16 的补丁,那么每张图像总共会得到 196 个补丁(也称为标记)。

随着分辨率的提高,补丁的数量也会增加,从而导致内存占用增加。

我们能否在不影响性能的情况下减少补丁的数量呢?Ryoo 等人在 TokenLearner 中研究了这个问题:视频的自适应时空标记化》中研究了这个问题。他们引入了一个名为 TokenLearner 的新模块,该模块能以自适应的方式帮助减少视觉转换器(ViT)使用的补丁数量。将 TokenLearner 纳入标准 ViT 架构后,他们能够减少模型使用的计算量(以 FLOPS 衡量)。

在本示例中,我们实现了 TokenLearner 模块,并用迷你 ViT 和 CIFAR-10 数据集演示了其性能。

导入

import keras
from keras import layers
from keras import ops
from tensorflow import data as tf_data


from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np

import math

超参数


请随时更改超参数并检查结果。对架构产生直觉的最好方法就是进行实验。

# DATA
BATCH_SIZE = 256
AUTO = tf_data.AUTOTUNE
INPUT_SHAPE = (32, 32, 3)
NUM_CLASSES = 10

# OPTIMIZER
LEARNING_RATE = 1e-3
WEIGHT_DECAY = 1e-4

# TRAINING
EPOCHS = 1

# AUGMENTATION
IMAGE_SIZE = 48  # We will resize input images to this size.
PATCH_SIZE = 6  # Size of the patches to be extracted from the input images.
NUM_PATCHES = (IMAGE_SIZE // PATCH_SIZE) ** 2

# ViT ARCHITECTURE
LAYER_NORM_EPS = 1e-6
PROJECTION_DIM = 128
NUM_HEADS = 4
NUM_LAYERS = 4
MLP_UNITS = [
    PROJECTION_DIM * 2,
    PROJECTION_DIM,
]

# TOKENLEARNER
NUM_TOKENS = 4

加载并准备 CIFAR-10 数据集

# Load the CIFAR-10 dataset.
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
(x_train, y_train), (x_val, y_val) = (
    (x_train[:40000], y_train[:40000]),
    (x_train[40000:], y_train[40000:]),
)
print(f"Training samples: {len(x_train)}")
print(f"Validation samples: {len(x_val)}")
print(f"Testing samples: {len(x_test)}")

# Convert to tf.data.Dataset objects.
train_ds = tf_data.Dataset.from_tensor_slices((x_train, y_train))
train_ds = train_ds.shuffle(BATCH_SIZE * 100).batch(BATCH_SIZE).prefetch(AUTO)

val_ds = tf_data.Dataset.from_tensor_slices((x_val, y_val))
val_ds = val_ds.batch(BATCH_SIZE).prefetch(AUTO)

test_ds = tf_data.Dataset.from_tensor_slices((x_test, y_test))
test_ds = test_ds.batch(BATCH_SIZE).prefetch(AUTO)
Training samples: 40000
Validation samples: 10000
Testing samples: 10000

数据扩增

扩增管道包括:

重新缩放
调整大小
随机裁剪(固定大小或随机大小)
随机水平翻转

请注意,图像数据增强层在推理时不应用数据转换。这意味着在调用这些层时,如果训练=假,它们的行为会有所不同。

位置嵌入模块

Transformer 架构由多头自我关注层和全连接前馈网络(MLP)作为主要组成部分。这两个组件都具有排列不变性:它们不考虑特征顺序。

为了克服这一问题,我们为标记注入了位置信息。

position_embedding 函数将位置信息添加到线性投影的标记中。

class PatchEncoder(layers.Layer):
    def __init__(self, num_patches, projection_dim):
        super().__init__()
        self.num_patches = num_patches
        self.position_embedding = layers.Embedding(
            input_dim=num_patches, output_dim=projection_dim
        )

    def call(self, patch):
        positions = ops.expand_dims(
            ops.arange(start=0, stop=self.num_patches, step=1), axis=0
        )
        encoded = patch + self.position_embedding(positions)
        return encoded

    def get_config(self):
        config = super().get_config()
        config.update({"num_patches": self.num_patches})
        return config

变换器的 MLP 模块


这是变换器的全连接前馈模块。

def mlp(x, dropout_rate, hidden_units):
    # Iterate over the hidden units and
    # add Dense => Dropout.
    for units in hidden_units:
        x = layers.Dense(units, activation=ops.gelu)(x)
        x = layers.Dropout(dropout_rate)(x)
    return x

令牌学习器模块

下图是该模块的图示概览(来源)。

TokenLearner 模块将图像形状的张量作为输入。然后,它将其通过多个单通道卷积层,提取不同的空间注意力图,并将注意力集中在输入的不同部分。然后,将这些注意力图按元素顺序与输入相乘,并对结果进行汇集。汇集后的输出可以看作是输入的汇总,其补丁数量(例如 8 个)远远少于原始输出(例如 196 个)。

使用多个卷积层有助于提高表现力。施加一种空间注意力有助于保留输入的相关信息。这两个部分对 TokenLearner 的运行都至关重要,尤其是当我们要大幅减少贴片数量时。

def token_learner(inputs, number_of_tokens=NUM_TOKENS):
    # Layer normalize the inputs.
    x = layers.LayerNormalization(epsilon=LAYER_NORM_EPS)(inputs)  # (B, H, W, C)

    # Applying Conv2D => Reshape => Permute
    # The reshape and permute is done to help with the next steps of
    # multiplication and Global Average Pooling.
    attention_maps = keras.Sequential(
        [
            # 3 layers of conv with gelu activation as suggested
            # in the paper.
            layers.Conv2D(
                filters=number_of_tokens,
                kernel_size=(3, 3),
                activation=ops.gelu,
                padding="same",
                use_bias=False,
            ),
            layers.Conv2D(
                filters=number_of_tokens,
                kernel_size=(3, 3),
                activation=ops.gelu,
                padding="same",
                use_bias=False,
            ),
            layers.Conv2D(
                filters=number_of_tokens,
                kernel_size=(3, 3),
                activation=ops.gelu,
                padding="same",
                use_bias=False,
            ),
            # This conv layer will generate the attention maps
            layers.Conv2D(
                filters=number_of_tokens,
                kernel_size=(3, 3),
                activation="sigmoid",  # Note sigmoid for [0, 1] output
                padding="same",
                use_bias=False,
            ),
            # Reshape and Permute
            layers.Reshape((-1, number_of_tokens)),  # (B, H*W, num_of_tokens)
            layers.Permute((2, 1)),
        ]
    )(
        x
    )  # (B, num_of_tokens, H*W)

    # Reshape the input to align it with the output of the conv block.
    num_filters = inputs.shape[-1]
    inputs = layers.Reshape((1, -1, num_filters))(inputs)  # inputs == (B, 1, H*W, C)

    # Element-Wise multiplication of the attention maps and the inputs
    attended_inputs = (
        ops.expand_dims(attention_maps, axis=-1) * inputs
    )  # (B, num_tokens, H*W, C)

    # Global average pooling the element wise multiplication result.
    outputs = ops.mean(attended_inputs, axis=2)  # (B, num_tokens, C)
    return outputs

变换器组

def transformer(encoded_patches):
    # Layer normalization 1.
    x1 = layers.LayerNormalization(epsilon=LAYER_NORM_EPS)(encoded_patches)

    # Multi Head Self Attention layer 1.
    attention_output = layers.MultiHeadAttention(
        num_heads=NUM_HEADS, key_dim=PROJECTION_DIM, dropout=0.1
    )(x1, x1)

    # Skip connection 1.
    x2 = layers.Add()([attention_output, encoded_patches])

    # Layer normalization 2.
    x3 = layers.LayerNormalization(epsilon=LAYER_NORM_EPS)(x2)

    # MLP layer 1.
    x4 = mlp(x3, hidden_units=MLP_UNITS, dropout_rate=0.1)

    # Skip connection 2.
    encoded_patches = layers.Add()([x4, x2])
    return encoded_patches

带有 TokenLearner 模块的 ViT 模型

def create_vit_classifier(use_token_learner=True, token_learner_units=NUM_TOKENS):
    inputs = layers.Input(shape=INPUT_SHAPE)  # (B, H, W, C)

    # Augment data.
    augmented = data_augmentation(inputs)

    # Create patches and project the pathces.
    projected_patches = layers.Conv2D(
        filters=PROJECTION_DIM,
        kernel_size=(PATCH_SIZE, PATCH_SIZE),
        strides=(PATCH_SIZE, PATCH_SIZE),
        padding="VALID",
    )(augmented)
    _, h, w, c = projected_patches.shape
    projected_patches = layers.Reshape((h * w, c))(
        projected_patches
    )  # (B, number_patches, projection_dim)

    # Add positional embeddings to the projected patches.
    encoded_patches = PatchEncoder(
        num_patches=NUM_PATCHES, projection_dim=PROJECTION_DIM
    )(
        projected_patches
    )  # (B, number_patches, projection_dim)
    encoded_patches = layers.Dropout(0.1)(encoded_patches)

    # Iterate over the number of layers and stack up blocks of
    # Transformer.
    for i in range(NUM_LAYERS):
        # Add a Transformer block.
        encoded_patches = transformer(encoded_patches)

        # Add TokenLearner layer in the middle of the
        # architecture. The paper suggests that anywhere
        # between 1/2 or 3/4 will work well.
        if use_token_learner and i == NUM_LAYERS // 2:
            _, hh, c = encoded_patches.shape
            h = int(math.sqrt(hh))
            encoded_patches = layers.Reshape((h, h, c))(
                encoded_patches
            )  # (B, h, h, projection_dim)
            encoded_patches = token_learner(
                encoded_patches, token_learner_units
            )  # (B, num_tokens, c)

    # Layer normalization and Global average pooling.
    representation = layers.LayerNormalization(epsilon=LAYER_NORM_EPS)(encoded_patches)
    representation = layers.GlobalAvgPool1D()(representation)

    # Classify outputs.
    outputs = layers.Dense(NUM_CLASSES, activation="softmax")(representation)

    # Create the Keras model.
    model = keras.Model(inputs=inputs, outputs=outputs)
    return model

如令牌学习器论文所示,将令牌学习器模块置于网络中间几乎总是有利的。

培训实用程序

def run_experiment(model):
    # Initialize the AdamW optimizer.
    optimizer = keras.optimizers.AdamW(
        learning_rate=LEARNING_RATE, weight_decay=WEIGHT_DECAY
    )

    # Compile the model with the optimizer, loss function
    # and the metrics.
    model.compile(
        optimizer=optimizer,
        loss="sparse_categorical_crossentropy",
        metrics=[
            keras.metrics.SparseCategoricalAccuracy(name="accuracy"),
            keras.metrics.SparseTopKCategoricalAccuracy(5, name="top-5-accuracy"),
        ],
    )

    # Define callbacks
    checkpoint_filepath = "/tmp/checkpoint.weights.h5"
    checkpoint_callback = keras.callbacks.ModelCheckpoint(
        checkpoint_filepath,
        monitor="val_accuracy",
        save_best_only=True,
        save_weights_only=True,
    )

    # Train the model.
    _ = model.fit(
        train_ds,
        epochs=EPOCHS,
        validation_data=val_ds,
        callbacks=[checkpoint_callback],
    )

    model.load_weights(checkpoint_filepath)
    _, accuracy, top_5_accuracy = model.evaluate(test_ds)
    print(f"Test accuracy: {round(accuracy * 100, 2)}%")
    print(f"Test top 5 accuracy: {round(top_5_accuracy * 100, 2)}%")

使用 TokenLearner 培训和评估 ViT

vit_token_learner = create_vit_classifier()
run_experiment(vit_token_learner)
 157/157 ━━━━━━━━━━━━━━━━━━━━ 303s 2s/step - accuracy: 0.1158 - loss: 2.4798 - top-5-accuracy: 0.5352 - val_accuracy: 0.2206 - val_loss: 2.0292 - val_top-5-accuracy: 0.7688
 40/40 ━━━━━━━━━━━━━━━━━━━━ 5s 133ms/step - accuracy: 0.2298 - loss: 2.0179 - top-5-accuracy: 0.7723
Test accuracy: 22.9%
Test top 5 accuracy: 77.22%

实验结果


我们进行了实验,在我们实现的迷你 ViT 中使用和不使用 TokenLearner(超参数与本例中介绍的相同)。以下是我们的结果:

TokenLearner# tokens in
TokenLearner
Top-1 Acc
(Averaged across 5 runs)
GFLOPsTensorBoard
N-56.112%0.0184Link
Y856.55%0.0153Link
N-56.37%0.0184Link
Y456.4980%0.0147Link
N- (# Transformer layers: 8)55.36%0.0359Link

在没有模块的情况下,TokenLearner 的性能始终优于我们的迷你 ViT。同样有趣的是,它也能超越我们的迷你 ViT 的更深版本(有 8 层)。咱们以前也看到类似的观察结果,并将其归功于 TokenLearner 的适应性。

我们还应该注意到,随着令牌学习器模块的加入,FLOPs 数量大大减少。随着 FLOPs 数的减少,TokenLearner 模块能够提供更好的结果。这与作者的研究结果非常吻合。

此外,咱们还为较小的训练数据机制推出了更新版本的 TokenLearner。

该版本不再使用 4 个具有小通道的卷积层来实现空间注意力,而是使用 2 个具有更多通道的分组卷积层。它还使用了 softmax 而不是 sigmoid。我们证实,在训练数据有限的情况下,比如使用 ImageNet1K 从头开始训练时,该版本的效果更好。

我们对该模块进行了实验,并在下表中对实验结果进行了总结:

# Groups# TokensTop-1 AccGFLOPsTensorBoard
4454.638%0.0149Link
8854.898%0.0146Link
4855.196%0.0149Link

请注意,我们在本例中使用了相同的超参数。我们的实现可以在本笔记本中找到。我们承认,使用这个新的 TokenLearner 模块得出的结果比预期的略有偏差,这可能会随着超参数的调整而有所缓解。

(注:为了计算模型的 FLOPs,我们使用了这个软件库中的实用程序。)

参数数量


你可能已经注意到,添加 TokenLearner 模块会增加基础网络的参数数量。但这并不意味着效率会降低,正如 Dehghani 等人的研究所示。贝洛等人也报告了类似的发现。令牌学习器模块有助于减少整个网络的 FLOPS,从而有助于减少内存占用。

最终说明


TokenFuser论文作者还提出了另一个名为 TokenFuser 的模块。

该模块有助于将 TokenLearner 输出的表示重映射回其原始空间分辨率。

要在 ViT 架构中重复使用 TokenLearner,TokenFuser 是必不可少的。

我们首先从令牌学习器中学习令牌,从变换器层建立令牌的表示,然后将表示重映射到原始空间分辨率,这样令牌学习器就能再次使用它。

请注意,在整个 ViT 模型中,如果不与 TokenFuser 配对,只能使用一次 TokenLearner 模块。
在视频中使用这些模块:咱们还建议 TokenFuser 与 Vision Transformers for Videos(阿纳布等人)搭配使用。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1641517.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Ubuntu TeamViewer安装与使用

TeamViewer是一款跨平台的专有应用程序,允许用户通过互联网连接从全球任何地方远程连接到工作站、传输文件以及召开在线会议。它适用于多种设备,例如个人电脑、智能手机和平板电脑。 TeamViewer在交通不便或偏远地区使用电脑问题时,将发挥重…

从零开始搭建Springboot项目脚手架1:新建项目

1、技术栈 SpringBoot 3.2.5: 2、 新建项目 使用SpringInitializr 选择Lombok、Configuration Processor、Spring Web,同时IDEA也要安装Lombok插件 删除多余的Maven目录、Maven文件,把HELP.md改成README.md。 当然前提是已经安装好Maven和配…

论文辅助笔记:Tempo之modules/prompt.py

1 get_prompt_param_cls 2 get_prompt_value 3 Prompt 类 3.1 _init_weights 3.2 forward

Windows设置Redis为开机自启动

前言 Redis作为当前最常用的当前缓存技术,基本上Web应用中都有使用。所以,每次我们在本地启动项目前,都必须将Redis服务端启动,否则项目就会启动失败。但是,每次都要去启动Redis就很麻烦,有没有办法做到开…

向量体系结构(5):步幅集中一分散

笔记来源《计算机体系结构 量化研究方法》 回答上一篇最后留下的问题 向量体系结构:向量执行时间-CSDN博客 (1)如何有效向量化多维矩阵运算? (2)向量处理器如何高效处理稀疏矩阵? 步幅 步…

一文了解python机器学习Sklearn

1.3 安装和配置Sklearn 要使用Sklearn库,首先需要安装Python和相应的库。在本教程中,我们将使用Python 3.x版本。可以使用以下命令安装Sklearn库: pip install scikit-learn安装完成后,可以在Python代码中导入Sklearn库&#xf…

WIN10 anaconda 安装 CondaError: Run ‘conda init‘ before ‘conda activate‘

1 下载 https://www.anaconda.com/download/success 2 安装 3 修改环境变量 安装后修改环境变量 4 winrun 进入命令窗口 输入cmd 输入 conda info 5 创建 虚拟环境 conda create -n yolov8 python3.8 -y 6 CondaError: Run ‘conda init’ before ‘conda activate’ c…

架构每日一学 2:架构师六个生存法则之一:架构必须有且仅有一个目标(一)

本文首发于公众号:腐烂的橘子 为什么有的架构活动没有正确的目标? 在每个架构活动启动之前,必须有且仅有一个正确的目标,这是架构设计的起点[1]。何为正确?正确就是要与公司的战略目标相匹配。否则系统会变得复杂和无…

基于Spring Boot的医疗服务系统设计与实现

基于Spring Boot的医疗服务系统设计与实现 开发语言:Java框架:springbootJDK版本:JDK1.8数据库工具:Navicat11开发软件:eclipse/myeclipse/idea 系统部分展示 医疗服务系统首页界面图,公告信息、医疗地图…

RHCE shell-第一次作业

要求: 1、判断当前磁盘剩余空间是否有20G,如果小于20G,则将报警邮件发送给管理员,每天检査- 次磁盘剩余空间。 2、判断web服务是否运行(1、查看进程的方式判断该程序是否运行,2、通过查看端口的方式 判断该程序是否运…

基于FPGA的数字信号处理(8)--RTL运算的溢出与保护

前言 在做加、减、乘、除等运算时,经常会发生 溢出 的情况。比如1个4bits的计数器(每个时钟累加1),在4’b1111 1 后,原本其期望值应该是 151 即16,但是4bits的寄存器能表示的最大值只是4‘b1111即15&…

Server 2022 IIS10 PHP 7.2.33 升级至 PHP 8.3 (8.3.6)

下载最新版本 PHP 8.3 (8.3.6),因为是 FastCGI 执行方式,选择 Non Thread Safe(非线程安全)。 若有以下提示: The mysqli extension is missing. Please check your PHP configuration. 或者 PHP Fatal error: Uncaught Error: Class &qu…

PDF Shaper Ultimate 免安装中文破姐版 v14.1

软件介绍 PDF Shaper是一套完整的多功能PDF编辑工具,可实现最高的生产力和文档安全性。它允许你分割,合并,水印,署名,优化,转换,加密和解密您的PDF文件,也可插入和移动页&#xff0…

每日OJ题_DFS爆搜深搜回溯剪枝①_力扣784. 字母大小写全排列

目录 力扣784. 字母大小写全排列 解析代码1_path是全局变量 解析代码2_path是函数参数 力扣784. 字母大小写全排列 784. 字母大小写全排列 难度 中等 给定一个字符串 s ,通过将字符串 s 中的每个字母转变大小写,我们可以获得一个新的字符串。 返回…

SpringSecurity6 学习

学习介绍 网上关于SpringSecurity的教程大部分都停留在6以前的版本 但是,SpringSecurity6.x版本后的内容进行大量的整改,网上的教程已经不能够满足 最新的版本使用。这里我查看了很多教程 发现一个宝藏课程,并且博主也出了一个关于SpringSec…

解决: 0x803f7001 在运行Microsoft Windows 非核心版本的计算机上,运行“ slui.exe 0x2a 0x803f7001 “以显示错误文本,激活win10步骤流程。

一. 解决 0x803F7001在运行Microsoft Windows非核心版本的计算机错误 首先,按下winR打开"运行",输入 regedit 后回车,打开注册表。   然后再注册表下输入地址HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SoftwareProt…

ssh远程访问windows系统下的jupyterlab

网上配置这一堆那一堆,特别乱,找了好久整理后发在这里 由于既想打游戏又想做深度学习,不舍得显卡性能白白消耗,这里尝试使用笔记本连接主机 OpenSSH 最初是为 Linux 系统开发的,现在也支持包括 Windows 和 macOS 在内…

【第三版 系统集成项目管理工程师】第2章 信息技术发展(知识总结)

持续更新。。。。。。。。。。。。。。。 【第2章】 信息技术发展 考情分析2. 1信息技术及其发展2.1.1 计算机软硬件-P501.计算机硬件2.计算机软件-P51 2.1.2计算机网络1.通信基础-P522.网络基础-P534.网络标准协议-P543.网络设备-P535.软件定义网络-P576.第五代移动通信技术-P…

【论文阅读】Tutorial on Diffusion Models for Imaging and Vision

1.The Basics: Variational Auto-Encoder 1.1 VAE Setting 自动编码器有一个输入变量x和一个潜在变量z Example. 获得图像的潜在表现并不是一件陌生的事情。回到jpeg压缩,使用离散余弦变换(dct)基φn对图像的底层图像/块进行编码。如果你给…

【Redis面试题】Redis常见的一些高频面试题

分享几个Redis入门级常见面试过程中遇到的题目! 你项目中哪里使用到了redis?可以讲一讲嘛 这个题目无论是大公司还是小公司都经常考,建议大家根据自己的项目做总结 redis的几种基础数据结构 redis为什么那么快? 1.基于内存实现:我们都知道内存读写是…