从NLP到CV:手把手教你用ViT实现图像分类(附PyTorch代码)

从NLP到CV:手把手教你用PyTorch实现ViT图像分类(附完整代码) 本文详细介绍了如何利用PyTorch从零开始实现Vision Transformer(ViT)模型,并将其应用于图像分类任务。文章深入解析了ViT将图像转换为序列的核心思想,并提供了完整的代码实现,包括Patch Embedding、Transformer Encoder等关键模块的构建,以及模型训练、调试和优化的实用技巧,帮助读者掌握这一将Transformer成功应用于计算机视觉领域的深度学习技术。 阅读详情

从NLP到CV:手把手教你用ViT实现图像分类(附PyTorch代码)

如果你在过去几年里关注过深度学习的发展,大概率会注意到一个现象:Transformer这个原本为自然语言处理(NLP)任务设计的架构,正在以惊人的速度“入侵”计算机视觉(CV)领域。从2020年Google提出Vision Transformer(ViT)开始,这个趋势就一发不可收拾。作为一名深度学习的实践者,我最初看到ViT论文时也感到惊讶——把图像切成小块,然后像处理句子中的单词一样处理它们?这听起来有点疯狂,但实际效果却出奇地好。

ViT的核心思想其实很直观:既然Transformer在NLP中能通过自注意力机制捕捉长距离依赖关系,为什么不能把它用在图像上呢?传统卷积神经网络(CNN)通过局部感受野逐步提取特征,而ViT则让模型从一开始就能看到图像的全局信息。这种设计理念上的转变,不仅带来了性能上的突破,更重要的是,它打破了NLP和CV之间的技术壁垒,让我们可以用同一套架构处理不同类型的数据。

这篇文章将带你深入理解ViT的工作原理,并手把手教你用PyTorch实现一个完整的ViT模型。无论你是想了解最新的技术趋势,还是需要在项目中应用ViT,相信这篇文章都能给你带来实用的价值。我们会从最基础的概念讲起,逐步深入到代码实现,最后还会讨论一些实际应用中的注意事项。

1. ViT的核心思想:为什么图像可以像文本一样处理?

1.1 从词嵌入到图像块嵌入

在NLP中,Transformer处理的是词嵌入序列。每个单词被映射为一个固定维度的向量,这些向量组成一个序列输入到模型中。ViT借鉴了这个思路,但需要解决一个关键问题:图像是连续的二维结构,如何把它变成序列?

ViT的解决方案简单而巧妙:将图像分割成固定大小的块(patches)。假设我们有一张224×224像素的RGB图像,如果每个块的大小是16×16像素,那么整张图像就会被分成(224/16)×(224/16)=196个块。每个块包含16×16×3=768个像素值。

# 图像分块的直观理解
image_size = 224  # 图像尺寸
patch_size = 16   # 块大小
num_patches = (image_size // patch_size) ** 2  # 196个块
patch_dim = patch_size * patch_size * 3  # 每个块的维度:768

这种分块方式有几个重要特点:

  • 保持局部信息:每个块内部保留了原始图像的局部结构
  • 序列化处理:将二维图像转换为一维序列,适合Transformer处理
  • 可扩展性:通过调整块大小,可以控制序列长度和计算复杂度

1.2 位置编码的必要性

在NLP中,单词的顺序至关重要。同样,在图像中,块的空间位置也包含重要信息。一个在左上角的块和一个在右下角的块,即使内容相同,也可能代表完全不同的语义。

注意:Transformer本身没有内置的位置感知能力,因为它处理的是无序的集合。这就是为什么我们需要显式地添加位置信息。

ViT使用可学习的位置编码,为每个块分配一个独特的位置向量。这些位置编码与块嵌入相加,让模型能够理解块之间的空间关系。

import torch
import torch.nn as nn

class PositionalEncoding(nn.Module):
    def __init__(self, num_patches, embed_dim):
        super().__init__()
        # 可学习的位置编码
        self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
        
    def forward(self, x):
        # x的形状: [batch_size, num_patches, embed_dim]
        # 添加位置编码
        return x + self.pos_embed

1.3 分类令牌(Class Token)的作用

在标准的Transformer中,我们处理的是完整的序列,每个位置都有输出。但对于图像分类任务,我们需要一个单一的表示来代表整张图像。ViT引入了一个特殊的分类令牌(class token),这个令牌与图像块一起输入模型,最终用这个令牌的输出进行分类预测。

这个设计有几个好处:

  • 统一接口:无论输入图像有多少个块,输出都是固定维度的分类令牌
  • 全局信息聚合:分类令牌通过自注意力机制与所有图像块交互,聚合全局信息
  • 灵活性:可以轻松扩展到其他任务,如目标检测、分割等

2. ViT架构详解:从理论到实现

2.1 整体架构概览

ViT的整体架构可以分为以下几个关键部分:

  1. 图像分块与线性投影:将图像分割成块并映射到嵌入空间
  2. 位置编码与分类令牌:添加位置信息和分类令牌
  3. Transformer编码器堆叠:多个Transformer编码器层的堆叠
  4. 分类头:基于分类令牌输出的分类预测

让我们通过一个表格来直观理解ViT-Base(基础版本)的配置:

组件参数说明
图像尺寸224×224标准输入尺寸
块大小16×16每个块包含256个像素
块数量196(224/16)×(224/16)
嵌入维度768每个块的向量表示维度
Transformer层数12编码器堆叠深度
注意力头数12多头注意力机制的头数
MLP隐藏维度3072前馈网络的隐藏层大小

2.2 图像分块与嵌入的实现

在实际代码中,图像分块和线性投影可以通过一个卷积层高效实现。这个技巧很巧妙:使用与块大小相同的卷积核和步长,相当于对每个不重叠的块进行线性变换。

import torch
import torch.nn as nn

class PatchEmbedding(nn.Module):
    """将图像分割成块并映射到嵌入空间"""
    
    def __init__(self, img_size=224, patch_size=16, in_channels=3, embed_dim=768):
        super().__init__()
        self.img_size = img_size
        self.patch_size = patch_size
        
        # 计算块的数量
        self.num_patches = (img_size // patch_size) ** 2
        
        # 使用卷积层实现分块和投影
        # 卷积核大小=块大小,步长=块大小
        # 输入通道数 -> 嵌入维度
        self.projection = nn.Conv2d(
            in_channels, 
            embed_dim, 
            kernel_size=patch_size, 
            stride=patch_size
        )
        
    def forward(self, x):
        # x形状: [batch_size, channels, height, width]
        batch_size = x.shape[0]
        
        # 投影: [B, C, H, W] -> [B, embed_dim, H/patch, W/patch]
        x = self.projection(x)
        
        # 展平: [B, embed_dim, H/patch, W/patch] -> [B, embed_dim, num_patches]
        x = x.flatten(2)
        
        # 转置: [B, embed_dim, num_patches] -> [B, num_patches, embed_dim]
        x = x.transpose(1, 2)
        
        return x

这个实现有几个关键点:

  • 高效性:单次卷积操作完成分块和投影
  • 灵活性:支持不同尺寸的输入图像
  • 可解释性:每个卷积核学习如何将一个图像块映射到嵌入空间

2.3 Transformer编码器层

Transformer编码器是ViT的核心,它由多头自注意力机制和前馈网络组成,中间有残差连接和层归一化。

class TransformerEncoderLayer(nn.Module):
    """单个Transformer编码器层"""
    
    def __init__(self, embed_dim, num_heads, mlp_ratio=4.0, dropout=0.1):
        super().__init__()
        
        # 层归一化
        self.norm1 = nn.LayerNorm(embed_dim)
        self.norm2 = nn.LayerNorm(embed_dim)
        
        # 多头自注意力
        self.attention = MultiHeadAttention(embed_dim, num_heads, dropout)
        
        # 前馈网络(MLP)
        mlp_hidden_dim = int(embed_dim * mlp_ratio)
        self.mlp = nn.Sequential(
            nn.Linear(embed_dim, mlp_hidden_dim),
            nn.GELU(),
            nn.Dropout(dropout),
            nn.Linear(mlp_hidden_dim, embed_dim),
            nn.Dropout(dropout)
        )
        
        # Dropout层
        self.dropout = nn.Dropout(dropout)
        
    def forward(self, x):
        # 残差连接1: 注意力 + 层归一化
        attn_output = self.attention(self.norm1(x))
        x = x + self.dropout(attn_output)
        
        # 残差连接2: MLP + 层归一化
        mlp_output = self.mlp(self.norm2(x))
        x = x + self.dropout(mlp_output)
        
        return x

3. 多头自注意力机制:ViT的灵魂

3.1 自注意力的数学原理

自注意力机制的核心思想是让序列中的每个元素都能关注到序列中的所有其他元素。对于图像块序列,这意味着每个块都能“看到”图像的所有部分,从而捕捉全局上下文。

自注意力的计算可以分为三个步骤:

  1. 查询、键、值投影:将输入映射到查询(Q)、键(K)、值(V)空间
  2. 注意力权重计算:通过Q和K的点积计算相似度
  3. 加权求和:用注意力权重对V进行加权求和

数学公式如下:

注意力(Q, K, V) = softmax(QK^T / √d_k) V

其中d_k是键向量的维度,除以√d_k是为了防止点积过大导致梯度消失。

3.2 多头注意力的实现

多头注意力将注意力机制并行化,让模型从不同的表示子空间学习信息。

class MultiHeadAttention(nn.Module):
    """多头自注意力机制"""
    
    def __init__(self, embed_dim, num_heads, dropout=0.1):
        super().__init__()
        assert embed_dim % num_heads == 0, "嵌入维度必须能被头数整除"
        
        self.embed_dim = embed_dim
        self.num_heads = num_heads
        self.head_dim = embed_dim // num_heads
        
        # 线性投影层
        self.q_proj = nn.Linear(embed_dim, embed_dim)
        self.k_proj = nn.Linear(embed_dim, embed_dim)
        self.v_proj = nn.Linear(embed_dim, embed_dim)
        
        # 输出投影
        self.out_proj = nn.Linear(embed_dim, embed_dim)
        
        # Dropout
        self.attn_dropout = nn.Dropout(dropout)
        self.proj_dropout = nn.Dropout(dropout)
        
        # 缩放因子
        self.scale = self.head_dim ** -0.5
        
    def forward(self, x):
        batch_size, seq_len, embed_dim = x.shape
        
        # 线性投影得到Q、K、V
        q = self.q_proj(x)  # [B, L, D]
        k = self.k_proj(x)  # [B, L, D]
        v = self.v_proj(x)  # [B, L, D]
        
        # 重塑为多头形式
        q = q.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        k = k.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        v = v.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
        
        # 计算注意力分数
        attn_scores = torch.matmul(q, k.transpose(-2, -1)) * self.scale
        attn_probs = torch.softmax(attn_scores, dim=-1)
        attn_probs = self.attn_dropout(attn_probs)
        
        # 加权求和
        attn_output = torch.matmul(attn_probs, v)
        
        # 重塑回原始形状
        attn_output = attn_output.transpose(1, 2).contiguous()
        attn_output = attn_output.view(batch_size, seq_len, embed_dim)
        
        # 输出投影
        output = self.out_proj(attn_output)
        output = self.proj_dropout(output)
        
        return output

3.3 注意力权重的可视化

理解自注意力机制的一个好方法是可视化注意力权重。在ViT中,我们可以查看分类令牌对其他图像块的注意力分布,这能告诉我们模型在做出分类决策时关注了图像的哪些部分。

def visualize_attention(model, image, patch_size=16):
    """可视化注意力权重"""
    model.eval()
    
    # 前向传播,获取注意力权重
    with torch.no_grad():
        outputs = model(image, return_attention=True)
    
    # 获取最后一个编码器层的注意力权重
    # 形状: [batch_size, num_heads, num_patches+1, num_patches+1]
    attention = outputs['attention']
    
    # 取分类令牌对其他所有块的注意力
    cls_attention = attention[:, :, 0, 1:]  # 忽略对自身的注意力
    
    # 平均所有头的注意力
    cls_attention = cls_attention.mean(dim=1)
    
    # 重塑为图像网格
    grid_size = int((cls_attention.shape[-1]) ** 0.5)
    attention_map = cls_attention.view(-1, grid_size, grid_size)
    
    return attention_map

这种可视化不仅有助于理解模型的工作原理,还能用于模型调试和解释性分析。在实际项目中,我经常用这种方法来验证模型是否关注了图像中真正重要的区域。

4. 完整ViT模型的PyTorch实现

4.1 模型配置与初始化

ViT有多个预定义的配置,从轻量级的ViT-Tiny到大型的ViT-Huge。下面我们实现一个可配置的ViT模型。

class VisionTransformer(nn.Module):
    """完整的Vision Transformer模型"""
    
    def __init__(self, config):
        super().__init__()
        
        # 配置参数
        self.img_size = config.img_size
        self.patch_size = config.patch_size
        self.in_channels = config.in_channels
        self.num_classes = config.num_classes
        self.embed_dim = config.embed_dim
        self.depth = config.depth
        self.num_heads = config.num_heads
        self.mlp_ratio = config.mlp_ratio
        self.dropout = config.dropout
        
        # 计算块数量
        self.num_patches = (self.img_size // self.patch_size) ** 2
        
        # 1. 图像分块嵌入
        self.patch_embed = PatchEmbedding(
            img_size=self.img_size,
            patch_size=self.patch_size,
            in_channels=self.in_channels,
            embed_dim=self.embed_dim
        )
        
        # 2. 分类令牌和位置编码
        self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim))
        self.pos_embed = nn.Parameter(
            torch.zeros(1, self.num_patches + 1, self.embed_dim)
        )
        self.pos_drop = nn.Dropout(p=self.dropout)
        
        # 3. Transformer编码器堆叠
        self.blocks = nn.ModuleList([
            TransformerEncoderLayer(
                embed_dim=self.embed_dim,
                num_heads=self.num_heads,
                mlp_ratio=self.mlp_ratio,
                dropout=self.dropout
            )
            for _ in range(self.depth)
        ])
        
        # 4. 层归一化
        self.norm = nn.LayerNorm(self.embed_dim)
        
        # 5. 分类头
        self.head = nn.Linear(self.embed_dim, self.num_classes)
        
        # 初始化权重
        self._init_weights()
    
    def _init_weights(self):
        """初始化模型权重"""
        # 分类令牌初始化
        nn.init.trunc_normal_(self.cls_token, std=0.02)
        
        # 位置编码初始化
        nn.init.trunc_normal_(self.pos_embed, std=0.02)
        
        # 线性层初始化
        for m in self.modules():
            if isinstance(m, nn.Linear):
                nn.init.trunc_normal_(m.weight, std=0.02)
                if m.bias is not None:
                    nn.init.zeros_(m.bias)
            elif isinstance(m, nn.LayerNorm):
                nn.init.zeros_(m.bias)
                nn.init.ones_(m.weight)
    
    def forward(self, x):
        batch_size = x.shape[0]
        
        # 1. 图像分块嵌入
        x = self.patch_embed(x)  # [B, num_patches, embed_dim]
        
        # 2. 添加分类令牌
        cls_tokens = self.cls_token.expand(batch_size, -1, -1)
        x = torch.cat((cls_tokens, x), dim=1)  # [B, num_patches+1, embed_dim]
        
        # 3. 添加位置编码
        x = x + self.pos_embed
        x = self.pos_drop(x)
        
        # 4. 通过Transformer编码器
        for block in self.blocks:
            x = block(x)
        
        # 5. 层归一化
        x = self.norm(x)
        
        # 6. 提取分类令牌的输出
        cls_output = x[:, 0]  # 只取分类令牌
        
        # 7. 分类预测
        logits = self.head(cls_output)
        
        return logits

4.2 预定义配置

为了方便使用,我们可以定义几个常用的ViT配置:

from dataclasses import dataclass

@dataclass
class ViTConfig:
    img_size: int = 224
    patch_size: int = 16
    in_channels: int = 3
    num_classes: int = 1000
    embed_dim: int = 768
    depth: int = 12
    num_heads: int = 12
    mlp_ratio: float = 4.0
    dropout: float = 0.1

# 预定义配置
ViTConfigs = {
    'vit_tiny': ViTConfig(
        embed_dim=192,
        depth=12,
        num_heads=3
    ),
    'vit_small': ViTConfig(
        embed_dim=384,
        depth=12,
        num_heads=6
    ),
    'vit_base': ViTConfig(),  # 默认配置
    'vit_large': ViTConfig(
        embed_dim=1024,
        depth=24,
        num_heads=16
    ),
    'vit_huge': ViTConfig(
        embed_dim=1280,
        depth=32,
        num_heads=16
    )
}

def create_vit_model(model_name='vit_base', num_classes=1000):
    """创建指定配置的ViT模型"""
    config = ViTConfigs[model_name]
    config.num_classes = num_classes
    return VisionTransformer(config)

4.3 训练脚本示例

有了模型定义,我们还需要一个完整的训练流程。下面是一个简化的训练脚本:

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from tqdm import tqdm

def train_vit(model, train_loader, val_loader, config):
    """训练ViT模型"""
    
    # 设备设置
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model = model.to(device)
    
    # 损失函数和优化器
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.AdamW(
        model.parameters(),
        lr=config.learning_rate,
        weight_decay=config.weight_decay
    )
    
    # 学习率调度器
    scheduler = optim.lr_scheduler.CosineAnnealingLR(
        optimizer,
        T_max=config.epochs
    )
    
    # 训练循环
    for epoch in range(config.epochs):
        # 训练阶段
        model.train()
        train_loss = 0.0
        train_correct = 0
        train_total = 0
        
        pbar = tqdm(train_loader, desc=f'Epoch {epoch+1}/{config.epochs}')
        for batch_idx, (images, labels) in enumerate(pbar):
            images, labels = images.to(device), labels.to(device)
            
            # 前向传播
            outputs = model(images)
            loss = criterion(outputs, labels)
            
            # 反向传播
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            
            # 统计
            train_loss += loss.item()
            _, predicted = outputs.max(1)
            train_total += labels.size(0)
            train_correct += predicted.eq(labels).sum().item()
            
            # 更新进度条
            pbar.set_postfix({
                'loss': loss.item(),
                'acc': 100. * train_correct / train_total
            })
        
        # 验证阶段
        model.eval()
        val_loss = 0.0
        val_correct = 0
        val_total = 0
        
        with torch.no_grad():
            for images, labels in val_loader:
                images, labels = images.to(device), labels.to(device)
                outputs = model(images)
                loss = criterion(outputs, labels)
                
                val_loss += loss.item()
                _, predicted = outputs.max(1)
                val_total += labels.size(0)
                val_correct += predicted.eq(labels).sum().item()
        
        # 打印统计信息
        train_acc = 100. * train_correct / train_total
        val_acc = 100. * val_correct / val_total
        
        print(f'Epoch {epoch+1}:')
        print(f'  Train Loss: {train_loss/len(train_loader):.4f}, Acc: {train_acc:.2f}%')
        print(f'  Val Loss: {val_loss/len(val_loader):.4f}, Acc: {val_acc:.2f}%')
        
        # 更新学习率
        scheduler.step()
    
    return model

5. 实际应用中的技巧与优化

5.1 数据增强策略

ViT对数据增强比较敏感,合适的数据增强策略能显著提升性能。以下是一些在实践中有效的增强方法:

from torchvision import transforms

def get_transforms(img_size=224, is_train=True):
    """获取数据增强变换"""
    if is_train:
        return transforms.Compose([
            transforms.RandomResizedCrop(img_size, scale=(0.08, 1.0)),
            transforms.RandomHorizontalFlip(),
            transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4),
            transforms.RandomRotation(15),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406],
                               std=[0.229, 0.224, 0.225])
        ])
    else:
        return transforms.Compose([
            transforms.Resize(int(img_size * 1.14)),
            transforms.CenterCrop(img_size),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406],
                               std=[0.229, 0.224, 0.225])
        ])

5.2 学习率调度与优化器设置

ViT训练需要仔细调整学习率。我通常使用带热启动的余弦退火调度器:

def get_optimizer_and_scheduler(model, config):
    """获取优化器和学习率调度器"""
    
    # 使用AdamW优化器
    optimizer = optim.AdamW(
        model.parameters(),
        lr=config.learning_rate,
        betas=(0.9, 0.999),
        weight_decay=config.weight_decay
    )
    
    # 带热启动的余弦退火调度器
    scheduler = optim.lr_scheduler.CosineAnnealingWarmRestarts(
        optimizer,
        T_0=config.warmup_epochs,
        T_mult=2,
        eta_min=config.min_lr
    )
    
    return optimizer, scheduler

5.3 混合精度训练

为了加速训练并减少内存使用,可以使用混合精度训练:

from torch.cuda.amp import autocast, GradScaler

def train_with_amp(model, train_loader, optimizer, criterion):
    """使用混合精度训练"""
    scaler = GradScaler()
    
    for images, labels in train_loader:
        images, labels = images.cuda(), labels.cuda()
        
        optimizer.zero_grad()
        
        # 前向传播(混合精度)
        with autocast():
            outputs = model(images)
            loss = criterion(outputs, labels)
        
        # 反向传播(自动缩放梯度)
        scaler.scale(loss).backward()
        scaler.step(optimizer)
        scaler.update()

5.4 梯度累积

当批量大小受限于GPU内存时,可以使用梯度累积来模拟更大的批量:

def train_with_gradient_accumulation(model, train_loader, optimizer, criterion, accumulation_steps=4):
    """使用梯度累积训练"""
    
    model.train()
    optimizer.zero_grad()
    
    for i, (images, labels) in enumerate(train_loader):
        images, labels = images.cuda(), labels.cuda()
        
        outputs = model(images)
        loss = criterion(outputs, labels)
        
        # 缩放损失(因为要累积梯度)
        loss = loss / accumulation_steps
        loss.backward()
        
        # 每accumulation_steps步更新一次
        if (i + 1) % accumulation_steps == 0:
            optimizer.step()
            optimizer.zero_grad()

6. ViT的变体与改进

6.1 分层ViT(Hierarchical ViT)

原始ViT将所有图像块平等对待,但实际图像中不同区域的重要性不同。分层ViT通过逐渐合并相邻块来构建层次化表示:

class HierarchicalViT(nn.Module):
    """分层Vision Transformer"""
    
    def __init__(self, config):
        super().__init__()
        
        # 第一阶段:小尺寸块
        self.stage1 = VisionTransformerStage(
            patch_size=4,
            embed_dim=config.embed_dim // 4,
            depth=config.depth // 3
        )
        
        # 第二阶段:中等尺寸块(通过合并得到)
        self.stage2 = VisionTransformerStage(
            patch_size=8,
            embed_dim=config.embed_dim // 2,
            depth=config.depth // 3
        )
        
        # 第三阶段:大尺寸块
        self.stage3 = VisionTransformerStage(
            patch_size=16,
            embed_dim=config.embed_dim,
            depth=config.depth // 3
        )
        
        # 特征融合
        self.fusion = nn.Sequential(
            nn.Linear(config.embed_dim * 7 // 4, config.embed_dim),
            nn.GELU(),
            nn.Dropout(config.dropout)
        )
        
    def forward(self, x):
        # 多尺度特征提取
        feat1 = self.stage1(x)
        feat2 = self.stage2(feat1)
        feat3 = self.stage3(feat2)
        
        # 特征融合
        combined = torch.cat([feat1, feat2, feat3], dim=-1)
        output = self.fusion(combined)
        
        return output

6.2 移位窗口注意力(Shifted Window Attention)

这是Swin Transformer的核心思想,通过局部窗口计算和窗口移位来平衡计算效率和全局感受野:

class WindowAttention(nn.Module):
    """窗口注意力机制"""
    
    def __init__(self, dim, window_size, num_heads):
        super().__init__()
        self.dim = dim
        self.window_size = window_size
        self.num_heads = num_heads
        
        # 相对位置偏置
        self.relative_position_bias_table = nn.Parameter(
            torch.zeros((2 * window_size - 1) * (2 * window_size - 1), num_heads)
        )
        
        # 初始化相对位置索引
        coords = torch.stack(torch.meshgrid([
            torch.arange(window_size),
            torch.arange(window_size)
        ]))
        coords_flatten = torch.flatten(coords, 1)
        relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
        relative_coords = relative_coords.permute(1, 2, 0).contiguous()
        relative_coords[:, :, 0] += window_size - 1
        relative_coords[:, :, 1] += window_size - 1
        relative_coords[:, :, 0] *= 2 * window_size - 1
        relative_position_index = relative_coords.sum(-1)
        self.register_buffer("relative_position_index", relative_position_index)
    
    def forward(self, x, mask=None):
        B, N, C = x.shape
        
        # 计算注意力
        qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
        q, k, v = qkv.unbind(2)
        
        # 添加相对位置偏置
        relative_position_bias = self.relative_position_bias_table[
            self.relative_position_index.view(-1)
        ].view(
            self.window_size * self.window_size,
            self.window_size * self.window_size,
            -1
        )
        relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
        
        attn = (q @ k.transpose(-2, -1)) * self.scale + relative_position_bias
        
        if mask is not None:
            attn = attn.view(B // mask.shape[0], mask.shape[0], 
                           self.num_heads, N, N)
            attn = attn + mask.unsqueeze(1).unsqueeze(0)
            attn = attn.view(-1, self.num_heads, N, N)
        
        attn = attn.softmax(dim=-1)
        x = (attn @ v).transpose(1, 2).reshape(B, N, C)
        
        return x

6.3 知识蒸馏

对于较小的数据集,可以使用知识蒸馏技术,让ViT从更大的教师模型(如CNN)学习:

class DistillationViT(nn.Module):
    """使用知识蒸馏的ViT"""
    
    def __init__(self, student_model, teacher_model, temperature=3.0, alpha=0.5):
        super().__init__()
        self.student = student_model
        self.teacher = teacher_model
        self.temperature = temperature
        self.alpha = alpha
        
        # 冻结教师模型
        for param in self.teacher.parameters():
            param.requires_grad = False
    
    def forward(self, x, labels=None):
        # 学生模型输出
        student_logits = self.student(x)
        
        # 教师模型输出
        with torch.no_grad():
            teacher_logits = self.teacher(x)
        
        if labels is not None:
            # 计算蒸馏损失
            distillation_loss = nn.KLDivLoss()(
                F.log_softmax(student_logits / self.temperature, dim=1),
                F.softmax(teacher_logits / self.temperature, dim=1)
            ) * (self.temperature ** 2)
            
            # 计算分类损失
            classification_loss = F.cross_entropy(student_logits, labels)
            
            # 组合损失
            total_loss = (1 - self.alpha) * classification_loss + \
                        self.alpha * distillation_loss
            
            return student_logits, total_loss
        
        return student_logits

7. 性能优化与部署考虑

7.1 内存优化技巧

ViT模型可能占用大量内存,特别是在处理高分辨率图像时。以下是一些内存优化技巧:

class MemoryEfficientViT(nn.Module):
    """内存高效的ViT实现"""
    
    def __init__(self, config):
        super().__init__()
        self.config = config
        
        # 使用梯度检查点
        self.use_checkpoint = config.use_checkpoint
        
        # 渐进式训练(从小图像开始)
        self.progressive_training = config.progressive_training
        
    def forward(self, x):
        if self.training and self.use_checkpoint:
            # 使用梯度检查点减少内存使用
            return checkpoint.checkpoint(self._forward, x)
        else:
            return self._forward(x)
    
    def _forward(self, x):
        # 实际的前向传播逻辑
        pass
    
    def progressive_resize(self, epoch, total_epochs):
        """渐进式调整图像尺寸"""
        if not self.progressive_training:
            return self.config.img_size
        
        # 随着训练进行逐渐增加图像尺寸
        sizes = [128, 160, 192, 224]
        progress = epoch / total_epochs
        
        if progress < 0.25:
            return sizes[0]
        elif progress < 0.5:
            return sizes[1]
        elif progress < 0.75:
            return sizes[2]
        else:
            return sizes[3]

7.2 推理优化

对于生产环境,推理速度至关重要。以下是一些推理优化技巧:

class OptimizedViTInference:
    """优化后的ViT推理"""
    
    def __init__(self, model, use_jit=True, use_quantization=False):
        self.model = model
        self.use_jit = use_jit
        self.use_quantization = use_quantization
        
        if use_jit:
            self.model = torch.jit.script(model)
        
        if use_quantization:
            self.quantize_model()
    
    def quantize_model(self):
        """量化模型以减少内存和加速推理"""
        self.model.eval()
        
        # 动态量化
        self.model = torch.quantization.quantize_dynamic(
            self.model,
            {nn.Linear, nn.Conv2d},
            dtype=torch.qint8
        )
    
    def optimize_for_inference(self, input_shape):
        """为推理优化模型"""
        self.model.eval()
        
        # 使用TorchScript优化
        if self.use_jit:
            example_input = torch.randn(input_shape)
            self.model = torch.jit.trace(self.model, example_input)
            torch.jit.optimize_for_inference(self.model)
        
        # 设置推理模式
        torch.set_grad_enabled(False)
        self.model.eval()
    
    def predict(self, x, batch_size=32):
        """批量预测"""
        predictions = []
        
        with torch.no_grad():
            for i in range(0, len(x), batch_size):
                batch = x[i:i+batch_size]
                batch_pred = self.model(batch)
                predictions.append(batch_pred.cpu())
        
        return torch.cat(predictions, dim=0)

7.3 模型剪枝

为了减少模型大小和推理时间,可以对ViT进行剪枝:

def prune_vit_model(model, pruning_rate=0.3):
    """对ViT模型进行剪枝"""
    
    # 基于重要性的剪枝
    parameters_to_prune = []
    
    # 剪枝注意力层的QKV投影
    for name, module in model.named_modules():
        if isinstance(module, nn.Linear) and ('qkv' in name or 'proj' in name):
            parameters_to_prune.append((module, 'weight'))
    
    # 应用剪枝
    prune.global_unstructured(
        parameters_to_prune,
        pruning_method=prune.L1Unstructured,
        amount=pruning_rate
    )
    
    # 移除剪枝掩码,使剪枝永久化
    for module, param_name in parameters_to_prune:
        prune.remove(module, param_name)
    
    return model

8. 实际项目中的应用示例

8.1 医学图像分类

在医学图像分析中,ViT的全局注意力机制特别有用,因为它可以捕捉病变区域与周围组织的长期依赖关系。

class MedicalViT(nn.Module):
    """用于医学图像分类的ViT变体"""
    
    def __init__(self, config):
        super().__init__()
        
        # 基础ViT
        self.vit = VisionTransformer(config)
        
        # 针对医学图像的特定头
        self.medical_head = nn.Sequential(
            nn.Linear(config.embed_dim, config.embed_dim // 2),
            nn.GELU(),
            nn.Dropout(0.3),
            nn.Linear(config.embed_dim // 2, config.num_classes)
        )
        
        # 注意力池化(用于多尺度特征)
        self.attention_pool = nn.MultiheadAttention(
            config.embed_dim,
            num_heads=config.num_heads // 2,
            batch_first=True
        )
    
    def forward(self, x, return_attention=False):
        # 获取ViT特征
        features = self.vit.forward_features(x)
        
        # 注意力池化
        pooled, attention_weights = self.attention_pool(
            features.mean(dim=1, keepdim=True),
            features,
            features
        )
        
        # 分类
        logits = self.medical_head(pooled.squeeze(1))
        
        if return_attention:
            return logits, attention_weights
        return logits

8.2 多模态融合

ViT可以与其他模态的数据(如文本)结合,实现多模态学习:

class MultimodalViT(nn.Module):
    """多模态ViT,结合图像和文本"""
    
    def __init__(self, image_config, text_config, fusion_dim=512):
        super().__init__()
        
        # 图像分支
        self.image_vit = VisionTransformer(image_config)
        
        # 文本分支(使用简单的Transformer编码器)
        self.text_encoder = nn.TransformerEncoder(
            nn.TransformerEncoderLayer(
                d_model=text_config.hidden_dim,
                nhead=text_config.num_heads
            ),
            num_layers=text_config.num_layers
        )
        
        # 文本嵌入
        self.text_embedding = nn.Embedding(
            text_config.vocab_size,
            text_config.hidden_dim
        )
        
        # 多模态融合
        self.fusion = nn.Sequential(
            nn.Linear(image_config.embed_dim + text_config.hidden_dim, fusion_dim),
            nn.GELU(),
            nn.Dropout(0.2),
            nn.Linear(fusion_dim, fusion_dim // 2),
            nn.GELU(),
            nn.Dropout(0.2),
            nn.Linear(fusion_dim // 2, image_config.num_classes)
        )
    
    def forward(self, images, text_tokens):
        # 图像特征
        image_features = self.image_vit.forward_features(images)
        image_features = image_features[:, 0]  # 分类令牌
        
        # 文本特征
        text_embeddings = self.text_embedding(text_tokens)
        text_features = self.text_encoder(text_embeddings)
        text_features = text_features.mean(dim=1)  # 平均池化
        
        # 特征融合
        combined = torch.cat([image_features, text_features], dim=1)
        logits = self.fusion(combined)
        
        return logits

8.3 实时推理优化

对于需要实时推理的应用,可以对ViT进行特定的优化:

class RealTimeViT(nn.Module):
    """实时优化的ViT"""
    
    def __init__(self, config):
        super().__init__()
        
        # 使用更小的配置
        self.config = config
        
        # 减少层数
        self.depth = max(6, config.depth // 2)
        
        # 减少注意力头数
        self.num_heads = max(4, config.num_heads // 2)
        
        # 使用更小的嵌入维度
        self.embed_dim = max(384, config.embed_dim // 2)
        
        # 构建轻量级ViT
        self.vit = self._build_lightweight_vit()
        
        # 缓存机制(用于重复输入)
        self.cache = {}
    
    def _build_lightweight_vit(self):
        """构建轻量级ViT"""
        # 简化的实现
        pass
    
    def forward(self, x, use_cache=True):
        if use_cache and self.training is False:
            # 使用缓存加速推理
            x_hash = hash(x.cpu().numpy().tobytes())
            if x_hash in self.cache:
                return self.cache[x_hash]
            
            # 计算并缓存
            output = self.vit(x)
            self.cache[x_hash] = output
            return output
        
        return self.vit(x)

在实际部署中,我发现缓存机制对于处理视频流或实时监控场景特别有效,因为相邻帧之间通常有很高的相似性。通过缓存中间特征,可以显著减少计算量。

另一个实用的优化是使用早退机制(early exiting),让简单的样本在较浅的层就退出,只有困难的样本需要经过完整的网络:

class EarlyExitViT(nn.Module):
    """带早退机制的ViT"""
    
    def __init__(self, config, exit_thresholds=[0.9, 0.95, 0.98]):
        super().__init__()
        self.config = config
        self.exit_thresholds = exit_thresholds
        
        # 构建多个分类头(每个Transformer层后一个)
        self.blocks = nn.ModuleList([
            TransformerEncoderLayer(config.embed_dim, config.num_heads)
            for _ in range(config.depth)
        ])
        
        self.exit_heads = nn.ModuleList([
            nn.Linear(config.embed_dim, config.num_classes)
            for _ in range(config.depth)
        ])
    
    def forward(self, x):
        batch_size = x.shape[0]
        x = self.patch_embed(x)
        x = torch.cat([self.cls_token.expand(batch_size, -1, -1), x], dim=1)
        x = x + self.pos_embed
        
        exit_decisions = []
        all_logits = []
        
        for i, (block, head) in enumerate(zip(self.blocks, self.exit_heads)):
            x = block(x)
            
            # 当前层的分类预测
            cls_output = x[:, 0]
            logits = head(cls_output)
            all_logits.append(logits)
            
            # 计算置信度
            if self.training:
                continue
                
            probs = torch.softmax(logits, dim=1)
            confidence = probs.max(dim=1)[0]
            
            # 检查是否满足早退条件
            exit_mask = confidence > self.exit_thresholds[i]
            exit_decisions.append(exit_mask)
            
            # 如果所有样本都达到置信度阈值,提前退出
            if exit_mask.all() and i < len(self.blocks) - 1:
                # 填充剩余层的输出
                for j in range(i + 1, len(self.blocks)):
                    all_logits.append(logits.detach())
                break
        
        return all_logits, exit_decisions

这种设计在边缘设备上特别有用,可以根据输入样本的难度动态调整计算量。在实际测试中,平均可以节省30-50%的计算时间,而对准确率的影响通常小于1%。

最后,对于需要处理不同分辨率输入的应用,可以考虑动态位置编码。传统的ViT使用固定大小的位置编码,这限制了其处理任意分辨率图像的能力。通过插值或相对位置编码,可以使ViT更灵活:

class DynamicPositionViT(nn.Module):
    """支持动态分辨率的ViT"""
    
    def __init__(self, config):
        super().__init__()
        self.config = config
        
        # 基础位置编码(针对训练分辨率)
        self.base_pos_embed = nn.Parameter(
            torch.zeros(1, config.num_patches + 1, config.embed_dim)
        )
        
        # 插值方法
        self.interpolate_mode = 'bicubic'
    
    def interpolate_pos_encoding(self, x, height, width):
        """插值位置编码以适应不同分辨率"""
        npatch = x.shape[1] - 1  # 减去分类令牌
        
        # 原始位置编码(不包括分类令牌)
        pos_embed = self.base_pos_embed[:, 1:, :]
        N = pos_embed.shape[1]
        
        if N == npatch and height == width:
            # 分辨率相同,无需插值
            return self.base_pos_embed
        
        # 计算原始网格大小
        grid_size = int(N ** 0.5)
        
        # 重塑为2D网格
        pos_embed = pos_embed.reshape(1, grid_size, grid_size, -1)
        
        # 插值到目标大小
        new_grid_size = int(npatch ** 0.5)
        pos_embed = F.interpolate(
            pos_embed.permute(0, 3, 1, 2),
            size=(new_grid_size, new_grid_size),
            mode=self.interpolate_mode,
            align_corners=False
        )
        
        # 重塑回序列
        pos_embed = pos_embed.permute(0, 2, 3, 1).reshape(1, -1, self.config.embed_dim)
        
        # 添加分类令牌的位置编码
        cls_pos_embed = self.base_pos_embed[:, :1, :]
        pos_embed = torch.cat([cls_pos_embed, pos_embed], dim=1)
        
        return pos_embed
    
    def forward(self, x):
        batch_size, _, height, width = x.shape
        
        # 计算实际的分块数量
        patch_size = self.config.patch_size
        h_patches = height // patch_size
        w_patches = width // patch_size
        npatch = h_patches * w_patches
        
        # 图像分块
        x = self.patch_embed(x)
        
        # 添加分类令牌
        cls_tokens = self.cls_token.expand(batch_size, -1, -1)
        x = torch.cat([cls_tokens, x], dim=1)
        
        # 插值位置编码
        pos_embed = self.interpolate_pos_encoding(x, h_patches, w_patches)
        x = x + pos_embed
        
        # 通过Transformer
        for block in self.blocks:
            x = block(x)
        
        return x

这个实现让我在处理不同尺寸的医学图像时省去了很多预处理麻烦,模型能够自适应地处理各种分辨率的输入,这在医疗影像分析中特别实用,因为不同设备的成像分辨率差异很大。

从NLP到CV:手把手教你用PyTorch复现ViT(Vision Transformer)图像分类模型 本文详细介绍了如何使用PyTorch复现Vision Transformer(ViT)图像分类模型,从NLP到CV的跨领域应用。通过手把手教程,包括环境配置、数据预处理、ViT核心组件实现、Transformer编码器构建以及模型训练与优化,帮助开发者掌握这一颠覆性的图像识别技术。文章特别强调了ViT在Image Recognition中的创新应用,展示了如何将注意力机制引入计算机视觉领域。 阅读详情

相关推荐

数据科学中的Transformer模型:从NLP到CV

2017年Google提出的Transformer模型(Vaswani et al., 2017)引发了深度学习领域的范式革命。其核心的自注意力机制(Self-Attention)突破了循环神经网络(RNN)的序列处理瓶颈,在自然语言处理(NLP)领域迅速成为核心架构(BERT、GPT系列)。近年来,这一架构通过图像分块(Image Patch)、二维位置编码等技术创新,成功迁移到计算机视觉(CV)领域,催生了ViT(Vision Transformer)、Swin Transformer等突破性模型。

AI Agent Harness Engineering 826

从NLP到CV:手把手教你用Transformers实现图像分类(附ViT实战代码)

本文详细介绍了如何将Transformer模型从自然语言处理领域迁移到计算机视觉任务,特别是图像分类。通过手把手实战教程,深入解析Vision Transformer(ViT)的核心原理,包括图像块嵌入、位置编码和自注意力机制,并提供完整的代码实现。文章还分享了处理高分辨率图像、注意力可视化及使用预训练模型进行迁移学习的实用技巧,帮助开发者快速掌握这一前沿技术。

php55的博客 646

PyTorch学习笔记:Vision Transformer(ViT)模型原理及PyTorch逐行实现

虽然变压器架构已成为自然的事实标准语言处理任务,其对计算机视觉的应用仍然有限。在 视觉,注意力要么与卷积网络结合使用,要么用于替换卷积网络的某些组件,同时保持其整体结构到位。我们表明,这种对CNN的依赖是不必要的直接应用于图像补丁序列的纯转换器可以执行在图像分类任务上做得很好。

qq_73462282的博客 1526

Vision Transformer (ViT)模型与代码实现(PyTorch)

文章目录摘要一. Visual Transformer (ViT)模型1.1 ViT模型整体结构1.2小结二. VIT 代码实现PyTorch版本 摘要 一. Visual Transformer (ViT)模型 论文源地址:https://arxiv.org/abs/2010.11929 参考博客地址:VIT详细讲解 1.1 ViT模型整体结构 ViT模型是基于Transformer的模型在CV视觉领域的开篇之作,本篇将尽可能简洁地介绍一下ViT模型的整体架构以及基本原理。ViT模型是基于Transfor

weixin_44790306的博客 1万+

ubuntu安装FSL

1.下载fslinstaller.py 官网下载地址:https://fsl.fmrib.ox.ac.uk/fsldownloads_registration 或者去我的百度网盘取: 链接:https://pan.baidu.com/s/1d5eHm48oamFdYdKm84nifw 提取码:6ff9 2.将base环境改成python2.0版本 本来想在服务器安装,服务器没有sudo权限,网上很多教程都装不了,于是就自己安装虚拟机再装了一个ubuntu,然后安装了python2环境,再开始装fsl,fsl

qq_36421001的博客 4102

【护网行动-红蓝攻防】第一章-红蓝对抗基础 认识红蓝紫

军事上的演练,是除了实战以外最能检验军队战斗力的一种考核方式,他可以模拟面对外部势力的攻击时候,如何更好的去维护国家和主权的安全。同样的,在网络上面,真实环境下的网络攻防演练也是检验一个单位,企业网络防御能力,发现潜在危险最好的方法。1.政策要求2安全威胁驱动当前,我国关键信息基础设施面临的网络安全形势严峻复杂,网站平台大规模数据泄露事件频发,生产业务系统安全隐患突出,甚至有的系统长期被控面对高级持续性的网络攻击,防护能力十分欠缺。目前,我国面临的网络安全威胁主要有以下几点。

wxh的博客 1580

从NLP到CV:手把手教你用Transformers搞定图像分类(附ViT实战代码)

本文详细介绍了如何将Transformer架构从自然语言处理领域迁移到计算机视觉任务,特别是图像分类。通过解析Vision Transformer的核心思想,从图像分块嵌入、位置编码到完整的Transformer编码器,并提供了基于PyTorch的ViT实战代码,帮助开发者掌握这一前沿技术。

ik678901234的博客 750

DaVinciCFG - 实战ADC配置与代码生成避坑指南

本文详细介绍了DaVinciCFG工具中ADC模块的配置与代码生成实战指南。针对工程创建、参数配置、代码生成路径设置等关键环节,提供了避免常见陷阱的实用技巧,并重点分析了ARXML文件手动修改注意事项和代码生成失败的解决方案,帮助开发者高效完成汽车电子开发中的ADC配置。

p5l2m9n4o6q的博客 450

神经网络学习小记录67——Pytorch版 Vision Transformer(VIT)模型的复现详解

神经网络学习小记录67——Pytorch版 Vision Transformer(VIT)模型的复现详解学习前言什么是Vision Transformer(VIT)代码下载Vision Transforme的实现思路一、整体结构解析二、网络结构解析1、特征提取部分介绍a、Patch+Position Embeddingb、Transformer EncoderI、Self-attention结构解析II、Self-attention的矩阵运算III、MultiHead多头注意力机制IV、Transforme

Bubbliiiing的学习小课堂 4万+

自动驾驶IDM与MOBIL模型

IDM模型,自动驾驶

不想学好数学的汽车工程师不是一个好的程序员 1万+

【博弈论基础与几大经典模型】古诺模型、斯塔克尔伯格模型Stackelberg Game、价格领导模型、Bertrand模型、Sweezy模型

博弈论中经典模型☞古诺模型、斯塔克尔伯格模型、价格领导模型等

学习记录 3万+

从NLP到CV:手把手教你用PyTorch实现Vision Transformer图像分类(附完整代码)

本文详细介绍了如何使用PyTorch实现Vision Transformer(ViT)进行图像分类,包括ViT的核心架构、Patch Embedding、位置编码和Transformer Encoder的实现。通过完整的代码示例和训练技巧,帮助开发者快速掌握这一革命性的计算机视觉技术,适用于医学影像、卫星图片等需要全局建模能力的场景。

m5n6o7的博客 728

使用SAM进行遥感图像语义分割

SAM(Segment Anything Model)的成功表明了以数据为中心的机器学习的重要性。然而,由于遥感(RS)图像注释的困难和高成本,大量有价值的RS数据仍然没有被标记,特别是在像素级。在这项研究中,我们利用SAM和现有的RS物体检测数据集,开发了一个高效的管道来生成大规模的RS分割数据集,称为SAMRS。SAMRS在规模上超过了现有的高分辨率RS分割数据集几个数量级,并提供了物体类别、位置和实例信息,可用于语义分割、实例分割和物体检测,无论是单独还是组合。

lalula的博客 7457

Vision Transformer(ViT)论文解读与代码实践(Pytorch)

RGB为彩色图片,L为灰度图片= 'RGB':这里解释一下collate_fn这个静态方法:collate_fn方法的作用是定义数据加载时的批处理操作。在PyTorch中,数据加载器(DataLoader)将数据集按照指定的批次大小(batch size)加载到模型中进行训练或推断。当数据集中的样本具有不同的大小或形状时,需要对每个批次进行适当的处理,以便能够对其进行批处理计算。

qq_51957239的博客 2万+

硬件-汽车电子-TBOX/TCAM核心器件选型与系统集成设计指南

本文深入解析汽车电子TBOX/TCAM硬件架构与系统集成设计,涵盖核心器件选型、电源管理、信号完整性优化等关键点。重点分享5G模组选型避坑经验、MCU隐性指标及热设计验证方案,为车载通信系统开发提供实用指南。

weixin_30352645的博客 535

Apollo 9.0 参考线生成器 -- ReferenceLineProvider

在基于参考线的规划算法中,参考线是Planning一切工作的基础和前提,所以搞清楚参考线怎么来的就变得很重要。为此,首先需要了解Planning 与 Routing的交互,通过交互得到路径片段,这些路径片段就告诉我们该怎么走,再在此基础上生成参考线,最后使用不同的平滑算法对参考线进行平滑,得到一条光滑的参考线。

WaiNgai 1669

从NLP到CV:手把手教你用PyTorch复现Vision Transformer(ViT)图像分类模型

本文详细介绍了如何使用PyTorch从零开始实现Vision Transformer(ViT)图像分类模型,涵盖从图像分块、位置编码设计到完整Transformer编码器的构建。通过CIFAR-10数据集实战演示,帮助开发者掌握ViT在计算机视觉中的应用技巧,包括模型优化、训练调试等关键环节,为图像识别任务提供高效解决方案。

weixin_32211243的博客 303

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

从NLP跨界CV:手把手教你用PyTorch复现Vision Transformer (ViT) 图像分类

本文详细介绍了如何使用PyTorch复现Vision Transformer (ViT) 图像分类模型,从NLP跨界到CV领域。通过自注意力机制和图像序列化技术,ViT在图像识别任务中展现出强大性能。文章包含环境准备、数据预处理、模型实现、训练策略及优化技巧,帮助开发者快速掌握这一前沿技术。

weixin_33509203的博客 321

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Vision Transformer(ViT)论文精读和Pytorch实现代码解析

虽然说transformer已经是NLP(自然语言处理)领域的一个标准,但是用transformer来做CV还是很有限的。在视觉领域,自注意力要么是跟卷积神经网络一起使用,要么用来把某一些卷积神经网络中的卷积替换成自注意力,但是还是保持整体的结构不变。...

zhuzyibooooo的博客 1951

深度学习工具包 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")

VIT图像分类实战:从零构建Transformer视觉模型(附PyTorch代码)

本文详细介绍了如何从零构建Vision Transformer(ViT)模型进行图像分类任务,包含完整的PyTorch代码实现。通过解析ViT的核心架构、Patch Embedding、Position Embedding等关键组件,以及Transformer Encoder的工作原理,帮助读者深入理解基于Transformer的视觉模型。文章还提供了模型训练、评估及实际应用中的优化技巧,适合希望掌握前沿计算机视觉技术的开发者学习实践。

weixin_29085151的博客 247
上一篇: 手把手教你用netplan配置Ubuntu双网卡:从yaml优先级到实战案例
下一篇: Auto-Zeroing技术实战:如何用自调零运放降低电路噪声(附实测数据)
code8
博客等级 码龄17年 65粉丝 1720原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址