Search code examples
pythontensorflowembeddingconv-neural-network

Tensorflow character-level CNN - input shape


I'm trying to add 2-stacked character-level CNNs into a larger neural network system but I'm getting ValueError for the input dimensions.

What I want to achieve is to get orthographic representations for the input words by replacing characters (according to capitalization, or being numeric or alphabetic) and feeding them into CNN. I'm aware that this can be achieved with LSTM/RNN but the requirements indicate using CNN so using another NN is not optional.

Most of the examples out there naturally uses image datasets (MNIST etc.) but not text datasets. So I'm confused and not sure how to "reshape" character embeddings so that they can be valid inputs for the CNN.

So here is the part of the code I'm trying to run:

# ...

# shape = (batch size, max length of sentence, max length of word)
self.char_ids = tf.placeholder(tf.int32, shape=[None, None, None],
                name="char_ids")

# ...

# Char embedding lookup
_char_embeddings = tf.get_variable(
        name="_char_embeddings",
        dtype=tf.float32,
        shape=[self.config.nchars, self.config.dim_char])
char_embeddings = tf.nn.embedding_lookup(_char_embeddings,
        self.char_ids, name="char_embeddings")

# Reshape for CNN?
s = tf.shape(char_embeddings)
char_embeddings = tf.reshape(char_embeddings, shape=[s[0]*s[1], self.config.dim_char, s[2]])

# Conv #1
conv1 = tf.layers.conv1d(
    inputs=char_embeddings,
    filters=64,
    kernel_size=3,
    padding="valid",
    activation=tf.nn.relu)

# Conv #2
conv2 = tf.layers.conv1d(
    inputs=conv1,
    filters=64,
    kernel_size=3,
    padding="valid",
    activation=tf.nn.relu)
pool2 = tf.layers.max_pooling1d(inputs=conv2, pool_size=2, strides=2)

# Dense Layer
output = tf.layers.dense(inputs=pool2, units=32, activation=tf.nn.relu)

# ...

And this is the error I'm getting:

File "/home/emre/blstm-crf-ner/model/ner_model.py", line 159, in add_word_embeddings_op activation=tf.nn.relu)
File "/home/emre/blstm-crf-ner/virtner/lib/python3.4/site-packages/tensorflow/python/layers/convolutional.py", line 411, in conv1d return layer.apply(inputs)
File "/home/emre/blstm-crf-ner/virtner/lib/python3.4/site-packages/tensorflow/python/layers/base.py", line 809, in apply return self.__call__(inputs, *args, **kwargs)
File "/home/emre/blstm-crf-ner/virtner/lib/python3.4/site-packages/tensorflow/python/layers/base.py", line 680, in __call__ self.build(input_shapes)
File "/home/emre/blstm-crf-ner/virtner/lib/python3.4/site-packages/tensorflow/python/layers/convolutional.py", line 132, in build raise ValueError('The channel dimension of the inputs '
ValueError: The channel dimension of the inputs should be defined. Found `None`.

Any help would be appreciated.
Thanks.

UPDATE

So after following through some blog posts 1, 2 and thanks to vijay m, I understand that we have to provide input dimensions beforehand (unlike providing sequence_lengths with RNN/LSTM). So here is the final code snippet:

# Char embedding lookup
_char_embeddings = tf.get_variable(
        name="_char_embeddings",
        dtype=tf.float32,
        shape=[self.config.nchars, self.config.dim_char])
char_embeddings = tf.nn.embedding_lookup(_char_embeddings,
        self.char_ids, name="char_embeddings")

# max_len_of_word: 20
# Just pad shorter words and truncate the longer ones.
s = tf.shape(char_embeddings)
char_embeddings = tf.reshape(char_embeddings, shape=[-1, self.config.dim_char, self.config.max_len_of_word])

# Conv #1
conv1 = tf.layers.conv1d(
    inputs=char_embeddings,
    filters=64,
    kernel_size=3,
    padding="valid",
    activation=tf.nn.relu)

# Conv #2
conv2 = tf.layers.conv1d(
    inputs=conv1,
    filters=64,
    kernel_size=3,
    padding="valid",
    activation=tf.nn.relu)
pool2 = tf.layers.max_pooling1d(inputs=conv2, pool_size=2, strides=2)

# Dense Layer
output = tf.layers.dense(inputs=pool2, units=32, activation=tf.nn.relu)

Solution

  • conv1d expects channel dimension to be defined during the creating of the graph. So you cant pass the dimension as None.

    You need to make the following changes :

    char_ids = tf.placeholder(tf.int32, shape=[None, max_len_sen, max_len_word],
                name="char_ids")
    #max_len_sen and max_len_word has to be set.
    
    #Reshapping for CNN, should be
    s = char_embeddings.get_shape()
    char_embeddings = tf.reshape(char_embeddings, shape=[-1, dim_char, s[2]])