当我包含BiLSTM层时,使用Tensorflow模型的形状秩问题

2024-04-23 09:35:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在开发带有tensorflow 2.3的NN模型时遇到了一个问题,该模型在我将BiLSTM层包含到模型中时立即出现。我尝试了一个自定义模型,但这是Keras文档页面中的一个,而且它也失败了

  • 输入形状不会有问题,因为这发生在编译时,并且输入数据尚未提供给模型
  • 在另一台机器上试过,它在同一版本的tensorflow上运行良好

我使用的代码是:

from tensorflow import keras
from tensorflow.keras import layers

max_features = 20000  # Only consider the top 20k words
maxlen = 200  # Only consider the first 200 words of each movie review

# Input for variable-length sequences of integers
inputs = keras.Input(shape=(None,), dtype="int32")
# Embed each integer in a 128-dimensional vector
x = layers.Embedding(max_features, 128)(inputs)
# Add 2 bidirectional LSTMs
x = layers.Bidirectional(layers.LSTM(64, return_sequences=True))(x)
x = layers.Bidirectional(layers.LSTM(64))(x)
# Add a classifier
outputs = layers.Dense(1, activation="sigmoid")(x)
model = keras.Model(inputs, outputs)
model.summary()

输出错误为:

InvalidArgumentError: Shape must be at least rank 3 but is rank 2 for '{{node BiasAdd}} = BiasAdd[T=DT_FLOAT, data_format="NCHW"](add, bias)' with input shapes: [?,256], [256].

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-7-dd69b7331e68> in <module>
      7 x = layers.Embedding(max_features, 128)(inputs)
      8 # Add 2 bidirectional LSTMs
----> 9 x = layers.Bidirectional(layers.LSTM(64, return_sequences=True))(x)
     10 x = layers.Bidirectional(layers.LSTM(64))(x)
     11 # Add a classifier

1条回答
网友
1楼 · 发布于 2024-04-23 09:35:47

我发现了问题,所以我回答我自己的问题

Keras中有一个设置,用于指定处理(并且仅影响)图像数据的方式

  • 频道持续时间。图像数据以三维数组表示,其中最后一个通道表示颜色通道,例如[行][列][通道]

  • 先播放频道。图像数据以三维数组表示,其中第一个通道表示颜色通道,例如[通道][行][列]

Keras对不同的后端保持不同的设置,这被设置为Tensorflow的最后一个通道,但在我们的星球上,它看起来是首先设置为通道的

谢天谢地,这可以手动设置,我通过以下方法解决了它:

tensorflow.keras.backend.set_image_data_format("channels_last")

在上述直接来自Keras文档的示例中,它将如下所示:

max_features = 20000  # Only consider the top 20k words
maxlen = 200  # Only consider the first 200 words of each movie review

tensorflow.keras.backend.set_image_data_format("channels_last") # <  THIS FIXES IT

# Input for variable-length sequences of integers
inputs = keras.Input(shape=(None,), dtype="int32")
# Embed each integer in a 128-dimensional vector
x = layers.Embedding(max_features, 128)(inputs)
# Add 2 bidirectional LSTMs
x = layers.Bidirectional(layers.LSTM(64, return_sequences=True))(x)
x = layers.Bidirectional(layers.LSTM(64))(x)
# Add a classifier
outputs = layers.Dense(1, activation="sigmoid")(x)
model = keras.Model(inputs, outputs)
model.summary()

我很惊讶这个设置使得LSTM无法实例化,并且不确定这是否应该被视为一个bug

More info on this topic

相关问题 更多 >