使用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
相关产品推荐
相关产品推荐

