PyTorch 实现动态输入

使用 PyTorch 实现动态输入:支持训练和推理输入维度不一致的 CNN 和 LSTM/GRU 模型

在深度学习中,处理不同大小的输入数据是一个常见的挑战。许多实际应用需要模型能够灵活地处理可变长度的输入。本文将介绍如何使用 PyTorch 实现支持动态输入的 CNN 和 LSTM/GRU 模型,并打印每一层的输入和输出。

  • 卷积神经网络(CNN):CNN 通常用于处理图像数据。它通过卷积层提取局部特征,并能够处理不同大小的输入图像。通过使用全局池化层,CNN 可以将不同大小的特征图转换为固定大小的输出。

  • 长短期记忆网络(LSTM)和门控循环单元(GRU):LSTM 和 GRU 是处理序列数据的 RNN 变体。它们能够捕捉时间序列中的长期依赖关系,并支持可变长度的输入序列。

模型搭建

1. CNN 模型

我们将构建一个简单的 CNN 模型,支持动态输入大小,并打印每一层的输入和输出。

python 复制代码
import torch
import torch.nn as nn
import torch.nn.functional as F

class DynamicCNN(nn.Module):
    def __init__(self):
        super(DynamicCNN, self).__init__()
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3)
        self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3)
        self.pool = nn.AdaptiveAvgPool2d((1, 1))  # 自适应池化层
        self.fc = nn.Linear(32, 10)  # 输出10个类别

    def forward(self, x):
        print(f'Input to CNN: {x.shape}')
        x = F.relu(self.conv1(x))
        print(f'Output after conv1: {x.shape}')
        x = F.relu(self.conv2(x))
        print(f'Output after conv2: {x.shape}')
        x = self.pool(x)
        print(f'Output after pooling: {x.shape}')
        x = x.view(x.size(0), -1)  # 展平
        x = self.fc(x)
        print(f'Output after fc: {x.shape}')
        return x

# 创建模型
cnn_model = DynamicCNN()

# 测试动态输入
input_tensor_cnn = torch.randn(1, 3, 64, 64)  # 输入形状为 (batch_size, channels, height, width)
output_cnn = cnn_model(input_tensor_cnn)
python 复制代码
Input to CNN: torch.Size([1, 3, 55, 64])
Output after conv1: torch.Size([1, 16, 53, 62])
Output after conv2: torch.Size([1, 32, 51, 60])
Output after pooling: torch.Size([1, 32, 1, 1])
Output after fc: torch.Size([1, 10])
python 复制代码
Input to CNN: torch.Size([1, 3, 64, 64])
Output after conv1: torch.Size([1, 16, 62, 62])
Output after conv2: torch.Size([1, 32, 60, 60])
Output after pooling: torch.Size([1, 32, 1, 1])
Output after fc: torch.Size([1, 10])

2. LSTM/GRU 模型

接下来,我们将构建一个支持动态输入的 LSTM 模型,并打印每一层的输入和输出。

python 复制代码
import torch
import torch.nn as nn


class DynamicLSTM(nn.Module):
    def __init__(self):
        super(DynamicLSTM, self).__init__()
        self.lstm = nn.LSTM(input_size=10, hidden_size=20, batch_first=True)
        self.fc = nn.Linear(20, 1)  # 输出一个值

    def forward(self, x):
        print(f'Input to LSTM: {x.shape}')
        x, _ = self.lstm(x)
        print(f'Output after LSTM: {x.shape}')
        x = self.fc(x[:, -1, :])  # 取最后一个时间步的输出
        print(f'Output after fc: {x.shape}')
        return x


# 创建模型
lstm_model = DynamicLSTM()

# 测试动态输入
input_tensor_lstm = torch.randn(5, 15, 10)  # 输入形状为 (batch_size, seq_length, input_size)
output_lstm = lstm_model(input_tensor_lstm)
python 复制代码
Input to LSTM: torch.Size([5, 15, 10])
Output after LSTM: torch.Size([5, 15, 20])
Output after fc: torch.Size([5, 1])
python 复制代码
Input to LSTM: torch.Size([5, 20, 10])
Output after LSTM: torch.Size([5, 20, 20])
Output after fc: torch.Size([5, 1])

代码说明

  1. DynamicCNN :该模型包含两个卷积层和一个全连接层。使用自适应平均池化层将特征图的大小调整为 (1, 1),从而支持不同大小的输入图像。每一层的输入和输出形状在前向传播中被打印出来。

  2. DynamicLSTM:该模型包含一个 LSTM 层和一个全连接层。LSTM 层能够处理可变长度的输入序列,输出的形状在前向传播中被打印出来。

相关推荐
AI022626 分钟前
探秘AI Agent软件公司:开启智能时代的创新引擎
人工智能
fīɡЙtīиɡ ℡2 小时前
AI 应用系统设计
java·开发语言·人工智能
小淮AI3 小时前
国际教育课程的本土化探索:以枫叶教育三十年为观察样本
大数据·人工智能
又折桃枝换酒钱3 小时前
VisCoder2:构建多语言可视化编码智能体(翻译与解读)
人工智能·信息可视化
AI绘画哇哒哒3 小时前
【建议收藏!】35岁后端血泪忠告,这3类人别硬转Agent(过来人亲述)
java·人工智能·后端·ai·程序员·大模型·agent
Chengbei113 小时前
DSH渗透测试插件dsh-pentest全新升级!适配DeepSeek Harness,可视化探索链路,一键搭建轻量化AI渗透测试环境。
人工智能·web安全·网络安全·微信·小程序·系统安全·安全架构
QN1幻化引擎3 小时前
DalinX Phi 性能突破:跨层秩保持对齐与意识涌现度量的实证研究
人工智能·ai·架构·agi·asi
NeilCarmack3 小时前
Deepseek-harness增加桌面版端序列:第 1 讲 · 命令解析:`pnpm dsh desktop` 的第一步
人工智能·agent·ai agent
聪明蛋子哟3 小时前
Stagehand v3多语言SDK:Python/Go/Rust/Java下的浏览器自动化统一方案
python·golang·rust