You need to enable JavaScript to run this app. 使用LSTM与GRU做二分类时GRU无法运行的代码问题求助
优惠活动
大模型
产品
解决方案
定价
更多

使用LSTM与GRU做二分类时GRU无法运行的代码问题求助

问题排查与修复方案

现有代码问题列表

  • 输出层重复定义:代码最后连续添加了两个Dense(1, activation='sigmoid')层,二分类任务仅需要1个最终输出层,多余的全连接层会导致输出维度、损失计算逻辑异常
  • GRU参数兼容问题:你为GRU设置了recurrent_dropout=0.2参数,该参数在新版TensorFlow/Keras中与CuDNN加速核不兼容,会触发运行时的兼容提示,缺失对应依赖时会直接终止运行
  • 模型结构逻辑问题:当前代码是将GRU和LSTM堆叠使用,如果你的开发目标是分别对比两种模型的二分类效果,该结构不符合预期,需要分别构建单GRU、单LSTM的两个独立模型
  • 冗余代码:连续调用两次model.summary()无实际作用,可删除冗余调用

修复后的参考代码

# BUILD THE MODEL
top_words = 10000
embedding_vector_length = 32
# 方案1:单独GRU模型,需要堆叠结构可自行调整
model = Sequential()
model.add(Embedding(top_words, embedding_vector_length, input_length=X.shape[1]))
# 去掉recurrent_dropout避免兼容问题,确有需要可以在compile时加run_eagerly=True参数
model.add(GRU(100, dropout=0.2, return_sequences=True))
model.add(GRU(100, dropout=0.2))
# 仅保留一个输出层
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='Adam', metrics=['accuracy'])
model.summary()

# 方案2:单独LSTM模型,按需选择运行即可
# model = Sequential()
# model.add(Embedding(top_words, embedding_vector_length, input_length=X.shape[1]))
# model.add(LSTM(100, dropout=0.2, return_sequences=True))
# model.add(LSTM(100, dropout=0.2))
# model.add(Dense(1, activation='sigmoid'))
# model.compile(loss='binary_crossentropy', optimizer='Adam', metrics=['accuracy'])
# model.summary()

特殊情况说明

如果必须要使用recurrent_dropout参数,在compile阶段添加参数run_eagerly=True即可解决兼容提示,缺点是会降低模型训练速度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 17:15:07