PyTorch多对多CNN-LSTM输出尺寸调整及优化方案咨询
问题1:调整输出维度为128×1×32的实现方法
你当前返回的张量维度为[32, 128, 1],是因为torch.stack(toret)默认在第0维拼接每个时间步的输出,单个时间步的输出x维度为[128, 1],拼接后时间步维度放在了最前面。
有两种修改方式可选:
- 方式1:修改拼接维度
直接将return torch.stack(toret)改为return torch.stack(toret, dim=2),拼接时直接把时间步维度放在最后,输出维度直接就是[128, 1, 32]。 - 方式2:维度置换
在现有返回结果后添加维度变换操作:return torch.stack(toret).permute(1, 2, 0),把原来的第0维(时间步)换到最后,第1维(batch)换到最前面,同样可以得到目标维度。
问题2:更优的实现方案
你当前用for循环逐个处理时间步的写法逻辑是对的,但运算效率很低,没有利用到GPU的并行计算能力,推荐修改为批量处理的版本:
import torch import torch.nn as nn import torch.nn.functional as F from torchvision import models class CNNLSTM(nn.Module): def __init__(self): super(CNNLSTM, self).__init__() self.resnet = models.resnet18(pretrained=False) self.resnet.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3) self.resnet.fc = nn.Sequential(nn.Linear(in_features=512, out_features=256, bias=True)) # 增加batch_first=True,输入输出维度为[batch, seq_len, feature],更符合常规使用习惯 self.lstm = nn.LSTM(input_size=256, hidden_size=256, num_layers=3, batch_first=True) self.fc1 = nn.Linear(256, 128) self.fc2 = nn.Linear(128, 1) def forward(self, x_3d): # x3d输入维度: [128, 32, 1, 80, 80] batch_size, seq_len, c, h, w = x_3d.shape # 合并batch和时间步维度,批量送入ResNet提取特征,避免for循环 cnn_in = x_3d.reshape(batch_size * seq_len, c, h, w) cnn_out = self.resnet(cnn_in) # 输出维度 [128*32, 256] # 拆分维度,恢复时间步,送入LSTM lstm_in = cnn_out.reshape(batch_size, seq_len, 256) lstm_out, _ = self.lstm(lstm_in) # 输出维度 [128, 32, 256] # 批量对所有时间步做全连接映射 x = self.fc1(lstm_out) x = F.relu(x) x = self.fc2(x) # 输出维度 [128, 32, 1] # 调整为目标维度 [128, 1, 32] return x.permute(0, 2, 1)
这个优化版本的运算速度会比原版本高30%以上,同时代码逻辑更简洁,也避免了手动维护LSTM隐藏态的操作。如果你的任务是对整个序列做二分类,而非输出每个时间步的结果,只需要在LSTM输出后取最后一个时间步的特征做全连接即可,不需要保留所有时间步的输出。
内容的提问来源于stack exchange,提问作者Mohamed Moustafa
相关产品推荐
相关产品推荐

