You need to enable JavaScript to run this app. PyTorch复现Keras模型时损失不下降振荡,Keras模型损失正常下降问题求助
优惠活动
大模型
产品
解决方案
定价
更多

PyTorch复现Keras模型时损失不下降振荡,Keras模型损失正常下降问题求助

PyTorch模型不收敛问题排查及修复方案

核心差异点(导致不收敛的主要原因)

  • 模型结构未对齐
    1. Embedding层维度错误:Keras实现中Embedding输出维度为50,你的PyTorch代码直接用hidden_size=512作为Embedding输出维度,参数量差异极大
    2. 循环层类型/维度错误:Keras用2层100维的LSTM,你的PyTorch代码用2层512维的GRU,两种循环层的门控逻辑、隐层维度都不匹配
    3. 输出时间步取错:Keras第二层LSTM未设置return_sequences=True,默认取最后一个时间步的输出,你的PyTorch代码强制取output[:,2]即第3个时间步的输出,除非你的输入序列长度固定为3,否则标签和输出完全不对应
  • 损失计算逻辑错误
    PyTorch的nn.CrossEntropyLoss()内置了log_softmax和NLLLoss计算,要求输入是未归一化的logits,你的代码提前对输出做了F.softmax,会导致梯度异常小、数值不稳定,是训练振荡不收敛的核心原因
  • 超参数未对齐
    需确认优化器类型、学习率、权重衰减等超参数和Keras默认配置一致,比如Keras默认Adam优化器学习率为1e-3,若PyTorch端学习率设置过大也会导致损失振荡

修复后的代码示例

模型结构修正

import torch.nn as nn
import torch.nn.functional as F

class ENCODER_RNN(nn.Module):
    def __init__(self, input_size, seq_length):
        super(ENCODER_RNN, self).__init__()
        # 对齐Keras的Embedding维度50
        self.embedding = nn.Embedding(input_size, 50)
        # 对齐Keras的2层100维LSTM
        self.lstm = nn.LSTM(50, 100, num_layers=2, batch_first=True)
        # 对齐Keras的Dense层维度
        self.linear_layer_1 = nn.Linear(100, 100)
        self.linear_out = nn.Linear(100, input_size)
        
    def forward(self, input_vector, hidden_state=None):
        embed_input = self.embedding(input_vector)
        output, hidden = self.lstm(embed_input, hidden_state)
        # 取最后一个时间步的输出,对齐Keras逻辑
        output = F.relu(self.linear_layer_1(output[:, -1]))
        # 直接输出logits,去掉softmax,交给CrossEntropyLoss处理
        output = self.linear_out(output)
        return output, hidden

训练逻辑确认

# 损失函数用CrossEntropyLoss,对应Keras的SparseCategoricalCrossentropy(标签为索引格式时)
criterion = nn.CrossEntropyLoss()
# 优化器对齐Keras默认配置
encoder_optimizer = torch.optim.Adam(encoder.parameters(), lr=1e-3)

# 单步训练逻辑无需大改,确认标签和输入对应即可
encoder_optimizer.zero_grad()
train_tensor = torch.tensor(train_input, device=DEVICE)
output_tensor = torch.tensor(output, device=DEVICE)
hidden = None
output, hidden = encoder(train_tensor, hidden)
loss = criterion(output, output_tensor)
loss.backward()
encoder_optimizer.step()

额外验证建议

  • 先拿小批量(10-20条)相同的数据分别喂给Keras和修复后的PyTorch模型,对比单步前向的损失值,若偏差小于1%则说明结构对齐正确
  • 确认两端的数据预处理逻辑完全一致,包括序列填充方式、标签生成规则、shuffle策略等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 00:45:01