1D CNN进行分类

时间:2017-08-24 13:56:18

标签: python python-2.7 tensorflow classification conv-neural-network

我正在构建一个卷积神经网络(使用Tensorflow),它应该对一维输入进行分类。

到目前为止,这是我的代码:

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)

当我运行上面的代码时,我收到以下错误:

  

追踪(最近一次通话):         文件" minex.py",第16行,in           correct = tf.nn.in_top_k(logits,y,1)         文件" /home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_nn_ops.py",   第1449行,in_top_k           targets = targets,k = k,name = name)         文件" /home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py",   第763行,在apply_op中           op_def = op_def)         文件" /home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py",   第2329行,在create_op中           set_shapes_for_outputs(RET)         文件" /home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py",   第1717行,在set_shapes_for_outputs中           shapes = shape_func(op)         文件" /home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py",   第1667行,在call_with_requiring中           return call_cpp_shape_fn(op,require_shape_fn = True)         文件" /home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/common_shapes.py",   第610行,在call_cpp_shape_fn中           debug_python_shape_fn,require_shape_fn)         文件" /home/jk/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/framework/common_shapes.py",   第676行,在_call_cpp_shape_fn_impl中           提出ValueError(err.message)       ValueError:Shape必须是等级2,但是对于' InTopK' (op:' InTopK')输入形状:[32,4,1] ,?。

根据错误,似乎我的问题与形状有关,但我不确定为什么会发生这种情况或如何纠正它。

1 个答案:

答案 0 :(得分:0)

您可以使用tf.squeeze从日志中删除外部维度。

你的最后一行可能会成为:

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

这会使logits张量的形状从[32,4,1]变为[32,4]。