Keras报告TypeError:不支持的操作数类型+:'NoneType'和'int'。

12

我是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'

那么我该如何处理它呢?

2个回答

8
RNN层的输入形状应为(num_timesteps, num_features),即每个样本由num_timesteps个时间步组成,每个时间步是长度为num_features的向量。此外,时间步数(即num_timesteps)可以是可变或未知的(即None),但特征数(即num_features)应在一开始就固定并指定。因此,您需要更改输入层的形状以与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)

谢谢你的回答! - david

0

我认为@today的回答非常清晰。然而,不完整。这里的关键是,如果您的输入不包含num_features,则必须在输入旁边添加一个Embedding层。

因此,如果您使用:

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

它也有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接