You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PyTorch构建ResNet18+LSTM融合模型?解决参数列表为空报错

问题解决:ResNet18+LSTM三分类模型实现及参数空列表报错修复

报错原因分析

你遇到的optimizer got an empty parameter list错误,根源是模型类的参数没有被PyTorch正确注册:

  1. 在Combine类的__init__里,直接执行self = self_res.to(device)会覆盖当前模型实例,导致后续定义的self.rnn、self.linear无法被PyTorch的参数追踪机制识别。
  2. 代码里forward方法调用了self.cnn,但__init__中从未定义过这个属性,属于引用错误。
  3. ResNet的输出维度和LSTM的input_size不匹配,原代码写的320没有依据,会导致后续维度错误。

修正后的完整代码

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import models

# 定义设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

class Combine(nn.Module):
    def __init__(self):
        super(Combine, self).__init__()
        # 加载预训练ResNet18,去掉最后的全连接层
        self.resnet = models.resnet18(pretrained=True)
        # 替换ResNet的fc层为Identity,保留特征提取部分(输出为512维特征)
        self.resnet.fc = nn.Identity()
        # LSTM模块:输入维度是ResNet的特征维度512,隐藏层64,单层,batch_first=True
        self.rnn = nn.LSTM(
            input_size=512, 
            hidden_size=64, 
            num_layers=1,
            batch_first=True)
        # 最终三分类的全连接层
        self.linear = nn.Linear(64, 3)

    def forward(self, x):
        # x的维度:(batch_size, timesteps, C, H, W)
        batch_size, timesteps, C, H, W = x.size()
        # 调整维度适配ResNet:(batch_size*timesteps, C, H, W)
        c_in = x.view(batch_size * timesteps, C, H, W)
        # ResNet提取特征,输出维度:(batch_size*timesteps, 512)
        c_out = self.resnet(c_in)
        # 调整维度适配LSTM:(batch_size, timesteps, 512)
        r_in = c_out.view(batch_size, timesteps, -1)
        # LSTM前向传播,取最后一个时间步的输出
        r_out, _ = self.rnn(r_in)
        # 取最后一个时间步的输出做分类:(batch_size, 64)
        r_out_last = r_out[:, -1, :]
        # 三分类输出
        output = self.linear(r_out_last)
        return F.log_softmax(output, dim=1)


class Args:
    def __init__(self):
        self.seed = 1
        self.batch_size = 50
        self.test_batch_size = 1000
        self.epochs = 10
        self.lr = 0.001  # 预训练模型建议用更小的学习率
        self.log_interval = 10

# 初始化模型、参数、损失函数和优化器
torch.manual_seed(Args().seed)
model = Combine().to(device)
args = Args()
criterion = nn.CrossEntropyLoss()
# 现在model.parameters()会包含ResNet(除了被替换的fc)、LSTM、linear的所有参数
optimizer = optim.Adam(model.parameters(), lr=args.lr)

关键修正点说明

  • 正确注册子模块:将ResNet作为self.resnet属性,而不是覆盖self,这样PyTorch会自动追踪其参数。
  • 适配特征维度:ResNet18去掉fc层后,输出特征是512维,因此LSTM的input_size设为512,避免维度不匹配错误。
  • 调整输入输出维度:明确各步骤的维度转换,确保从时序图像输入到特征提取、LSTM处理、最终分类的维度一致。
  • 学习率调整:使用预训练ResNet时,建议用更小的学习率(比如0.001),避免破坏预训练权重。

训练注意事项

你的输入数据维度需要是(batch_size, timesteps, 3, H, W),其中:

  • timesteps是每个样本的时序步数(比如视频的帧数)
  • 3是图像通道数(RGB)
  • H、W是图像的高和宽(需要满足ResNet的输入要求,比如224x224)

内容的提问来源于stack exchange,提问作者Clara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:00:42