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

Keras-TCN训练出现‘梯度不存在’警告,求排查原因及环境复现情况

问题:训练TCN模型时触发梯度不存在警告的原因分析

运行下方代码时触发如下警告:

Gradients do not exist for variables ['kernel', 'bias'] when minimizing the loss. If using model.compile(), did you forget to provide a loss argument?

请问该警告在相同环境中是否会出现?引发该警告的原因是什么?

from keras.layers import GlobalMaxPooling1D, Dense, Input
from keras.models import Sequential 
import keras
from tcn import TCN
import numpy as np
import warnings
import sys

warnings.filterwarnings("error") # Convert warnings to exceptions
try:
    # Your code here
    Modell = Sequential()
    # TCN
    Modell.add(Input(shape=(None, 4)))
    Modell.add( TCN(nb_filters=2, kernel_size=91, nb_stacks=1, dilations=[1], padding='causal', 
                    use_skip_connections=True, dropout_rate=0.0, return_sequences=True, activation='relu') )
    Modell.add(GlobalMaxPooling1D())   
    # DENSE
    Modell.add(Dense(4, activation='relu'))
    Modell.add(Dense(1, activation='relu'))
    Modell.add(Dense(4, activation='softmax'))
    Modell.compile(optimizer=keras.optimizers.Adam(learning_rate=0.006712461356073618), loss='SparseCategoricalCrossentropy', metrics=['sparse_categorical_accuracy'])
    batch = np.array([[-1.1,  0.5 , 0.9 , 0.02],
            [-1.0024, -0.18,  0.9, 0.02],
            [-1.0027, -0.52,  0.9, 0.02]])
    labels_batch = 1
    history = Modell.fit(np.array([batch]), np.array([labels_batch]), epochs=1, verbose=0)
except Warning as e:
    print(f"Warning encountered: {e}")
    sys.exit(1)  # Exit the program with a status code

版本信息

  • tf: 2.16.1
  • keras: 3.4.1
  • keras-tcn: 3.5.0

解答

在上述版本环境中运行代码确实会触发该警告,核心原因是模型中间层的设计导致梯度无法反向传播到TCN层的参数:

  1. relu激活的死区导致梯度断裂
    模型在Dense(4, relu)之后加入了Dense(1, relu)层,将特征维度直接压缩到1。在训练初始阶段,该层的输出很容易被relu激活为0,而relu在输入≤0时导数为0,这会直接切断梯度的反向传播路径,使得前面TCN层的kernel和bias参数无法得到更新,因此框架会警告这些变量的梯度不存在。

  2. 不必要的维度压缩加剧问题
    从特征流向来看,GlobalMaxPooling1D输出的特征已经可以直接用于后续分类层,中间加入的Dense(1, relu)属于冗余的维度压缩,不仅没有提升模型能力,反而制造了梯度传播的障碍。

修复建议

  • 直接移除Dense(1, activation='relu')层,让特征从Dense(4, relu)直接流向输出分类层;
  • 如果必须调整特征维度,可改用LeakyReLU等不会产生死区的激活函数,或选择大于1的中间维度(如2、3),降低梯度断裂的概率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 13:07:19