dav*_*vid 6 python machine-learning keras tensorflow rnn
我是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)
Run Code Online (Sandbox Code Playgroud)
错误:
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'
Run Code Online (Sandbox Code Playgroud)
那么我该如何处理呢?
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
Run Code Online (Sandbox Code Playgroud)
然后,您还需要更改输入数据的形状(即data),以使其与您指定的输入形状一致(即其形状必须为(num_samples, num_timesteps, num_features))。
附带说明,您可以通过SimpleRNN直接使用RNN层来更简单地定义该层:
label = keras.layers.SimpleRNN(units=5, activation='softmax')(inputs)
Run Code Online (Sandbox Code Playgroud)