Keras reports TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Keras reports TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

我是 Keras 的初学者,只是写了一个玩具示例。它报告 TypeError。代码及报错如下:

代码:

inputs = keras.Input(shape=(3, ))

cell = keras.layers.SimpleRNNCell(units=5, activation='softmax')
label = keras.layers.RNN(cell)(inputs)

model = keras.models.Model(inputs=inputs, outputs=label)
model.compile(optimizer='rmsprop',
              loss='mae',
              metrics=['acc'])

data = np.array([[1, 2, 3], [3, 4, 5]])
labels = np.array([1, 2])
model.fit(x=data, y=labels)

错误:

Traceback (most recent call last):
    File "/Users/david/Documents/code/python/Tensorflow/test.py", line 27, in <module>
        run()
    File "/Users/david/Documents/code/python/Tensorflow/test.py", line 21, in run
        label = keras.layers.RNN(cell)(inputs)
    File "/Users/david/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/layers/recurrent.py", line 619, in __call__
...
    File "/Users/david/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py", line 473, in __call__
        scale /= max(1., (fan_in + fan_out) / 2.)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

那我该如何处理呢?

RNN 层的输入将具有 (num_timesteps, num_features) 的形状,即每个样本由 num_timesteps 个时间步长组成,其中每个时间步长是一个长度为 num_features 的向量。此外,时间步长的数量(即 num_timesteps)可以是可变的或未知的(即 None),但特征的数量(即 num_features)应该是固定的并从一开始就指定。因此,需要改变Input层的形状,使其与RNN层保持一致。例如:

inputs = keras.Input(shape=(None, 3))  # variable number of timesteps each with length 3
inputs = keras.Input(shape=(4, 3))     # 4 timesteps each with length 3
inputs = keras.Input(shape=(4, None))  # this is WRONG! you can't do this. Number of features must be fixed

然后,您还需要更改输入数据的形状(即data)以及与您指定的输入形状一致(即它必须具有(num_samples, num_timesteps, num_features)的形状).

附带说明一下,您可以直接使用 SimpleRNN 层来更简单地定义 RNN 层:

label = keras.layers.SimpleRNN(units=5, activation='softmax')(inputs)

我觉得@today的回答很明确了。然而,并不完整。这里的关键是,如果你的输入不包含 num_features,你必须在输入旁边创建一个 Embedding 层。

因此,如果您使用:

inputs = keras.Input(shape=(3,))
embedding = Embedding(voc_size, embed_dim, ..)
X = embedding(inputs)

它也有效。