Keras 报告 TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
问题:Keras 报告 TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' 我是 Keras 的初学者,只是写一个玩具示例。它报告了一个TypeError。代码和错误如下: 代码: inputs = keras.Input(shape=(3, )) cell = keras.layers.SimpleRNNCell(
·
问题:Keras 报告 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)
更多推荐
已为社区贡献126494条内容
所有评论(0)