2
votes

I am building a convolutional neural network (with Tensorflow) that should classify one-dimensional inputs.

Here is my code so far:

import tensorflow as tf

n_outputs = 1
batch_size = 32
x = tf.placeholder(tf.float32, [batch_size, 10, 1])

filt = tf.zeros([3, 1, 1])

output = tf.nn.conv1d(x, filt, stride=2, padding="VALID")

y = tf.placeholder(tf.int32)
logits = tf.layers.dense(output, n_outputs)
xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits)
correct = tf.nn.in_top_k(logits, y, 1)

When I run the code above, I get the following error:

Traceback (most recent call last): File "minex.py", line 16, in correct = tf.nn.in_top_k(logits, y, 1) File "/home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_nn_ops.py", line 1449, in in_top_k targets=targets, k=k, name=name) File "/home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 763, in apply_op op_def=op_def) File "/home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2329, in create_op set_shapes_for_outputs(ret) File "/home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1717, in set_shapes_for_outputs shapes = shape_func(op) File "/home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1667, in call_with_requiring return call_cpp_shape_fn(op, require_shape_fn=True) File "/home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/common_shapes.py", line 610, in call_cpp_shape_fn debug_python_shape_fn, require_shape_fn) File "/home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/common_shapes.py", line 676, in _call_cpp_shape_fn_impl raise ValueError(err.message) ValueError: Shape must be rank 2 but is rank 3 for 'InTopK' (op: 'InTopK') with input shapes: [32,4,1], ?.

Based on the error, it seems that my problem is with the shapes, but I am not sure why is it happening or how to correct it.

1

1 Answers

0
votes

You can use tf.squeeze to remove the outer dimension from your logits.

Your last line could become:

correct = tf.nn.in_top_k(tf.squeeze(logits), y, 1)

That will bring the shape of the logits tensor from [32, 4, 1] to [32, 4].