Keras TimeDistributed Conv1D Error

旧街凉风 提交于 2019-12-13 12:35:28

问题


This is my code:

cnn_input = Input(shape=(cnn_max_length,)) 
emb_output = Embedding(num_chars + 1, output_dim=32, input_length=cnn_max_length, trainable=True)(cnn_input)
output = TimeDistributed(Convolution1D(filters=128, kernel_size=4, activation='relu'))(emb_output)

I want to train a character-level CNN sequence labeler and I keep receiving this error:

Traceback (most recent call last):
  File "word_lstm_char_cnn.py", line 24, in <module>
    output = kl.TimeDistributed(kl.Convolution1D(filters=128, kernel_size=4, activation='relu'))(emb_output)
  File "/home/user/anaconda3/envs/thesisenv/lib/python3.6/site-packages/keras/engine/base_layer.py", line 457, in __call__
    output = self.call(inputs, **kwargs)
es/keras/layers/wrappers.py", line 248, in call
    y = self.layer.call(inputs, **kwargs)
  File "/home/user/anaconda3/envs/thesisenv/lib/python3.6/site-packages/keras/layers/convolutional.py", line 160, in call
    dilation_rate=self.dilation_rate[0])
  File "/home/user/anaconda3/envs/thesisenv/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 3526, in conv1d
    data_format=tf_data_format)
  File "/home/user/anaconda3/envs/thesisenv/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py", line 779, in convolution
    data_format=data_format)
  File "/home/user/anaconda3/envs/thesisenv/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py", line 828, in __init__
    input_channels_dim = input_shape[num_spatial_dims + 1]
  File "/home/user/anaconda3/envs/thesisenv/lib/python3.6/site-packages/tensorflow/python/framework/tensor_shape.py", line 615, in __getitem__
    return self._dims[key]
IndexError: list index out of range

The input is 3D, as it should be. If I change the input shape I receive this error:

ValueError: Input 0 is incompatible with layer time_distributed_1: expected ndim=3, found ndim=4

回答1:


Recommended solution: There is no need to use TimeDistributed in this case. You can fix the issue with following piece of code:

output = Convolution1D(filters=128, kernel_size=4, activation='relu')(emb_output)

Just in case, if you like to use TimeDistributed you can do something like:

output = TimeDistributed(Dense(100,activation='relu'))(emb_output)

Not recommended: According to docs:

This wrapper applies a layer to every temporal slice of an input.

The input to the TimeDistributed is something like batch_size * seq_len * emb_size. When Conv1D apply to each sequence, it needs 2 dimensions but found only one.

You can fix the problem by adding one dimension to your sequences:

TimeDistributed(Conv1D(100, 1))(keras.backend.reshape(emb, [-1, sequence_len, embeding_dim, 1]))


来源:https://stackoverflow.com/questions/52008598/keras-timedistributed-conv1d-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!