【问题标题】:classification with LSTM RNN in tensorflow, ValueError: Shape (1, 10, 5) must have rank 2在张量流中使用 LSTM RNN 进行分类,ValueError: Shape (1, 10, 5) must have rank 2
【发布时间】:2017-02-04 13:13:49
【问题描述】:

我正在尝试在 tensorflow 中设计一个简单的 lstm。我想将一个数据序列分类为从 1 到 10 的类。

我有 10 个时间戳和数据 X。我现在只采用一个序列,所以我的批量大小 = 1。 在每个时期,都会生成一个新序列。例如 X 是一个像这样的 numpy 数组-

X [[ 2.52413028  2.49449348  2.46520466  2.43625973  2.40765466  2.37938545
     2.35144815  2.32383888  2.29655379  2.26958905]]

为了使其适合 lstm 输入,我首先将其转换为张量,然后对其进行重构(batch_size、sequence_lenght、输入维度)-

X= np.array([amplitude * np.exp(-t / tau)])
print 'X', X

#Sorting out the input
train_input = X
train_input = tf.convert_to_tensor(train_input)
train_input = tf.reshape(train_input,[1,10,1])
print 'ti', train_input

对于输出,我在 1 到 10 的类别范围内生成一个热编码标签。

#------------sorting out the output
train_output= [int(math.ceil(tau/resolution))]
train_output= one_hot(train_output, num_labels=10)
print 'label', train_output

train_output = tf.convert_to_tensor(train_output)

>>label [[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]]

然后我为张量流图创建了占位符,制作了 lstm 单元格并给出了权重和偏差-

data = tf.placeholder(tf.float32, shape= [batch_size,len(t),1])
target = tf.placeholder(tf.float32, shape = [batch_size, num_classes])

cell = tf.nn.rnn_cell.LSTMCell(num_hidden)
output, state = rnn.dynamic_rnn(cell, data, dtype=tf.float32)

weight = tf.Variable(tf.random_normal([batch_size, num_classes, 1])),
bias = tf.Variable(tf.random_normal([num_classes]))

#training
prediction = tf.nn.softmax(tf.matmul(output,weight) + bias)
cross_entropy = -tf.reduce_sum(target * tf.log(prediction))
optimizer = tf.train.AdamOptimizer()
minimize = optimizer.minimize(cross_entropy)

到目前为止,我已经编写了代码,但在训练步骤中出现了错误。它与输入形状有关吗?这是回溯---

Traceback(最近一次调用最后一次):

  File "/home/raisa/PycharmProjects/RNN_test1/test3.py", line 66, in <module>
prediction = tf.nn.softmax(tf.matmul(output,weight) + bias)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 1036, in matmul
name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 911, in _mat_mul
transpose_b=transpose_b, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 655, in apply_op
op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2156, in create_op
set_shapes_for_outputs(ret)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1612, in set_shapes_for_outputs
shapes = shape_func(op)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/common_shapes.py", line 81, in matmul_shape
a_shape = op.inputs[0].get_shape().with_rank(2)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_shape.py", line 625, in with_rank
raise ValueError("Shape %s must have rank %d" % (self, rank))
ValueError: Shape (1, 10, 5) must have rank 2

【问题讨论】:

    标签: python tensorflow deep-learning recurrent-neural-network lstm


    【解决方案1】:

    查看您的代码,您的 rnn 输出的维度应为 batch_size x 1 x num_hidden,而您的 w 的维度应为 batch_size x num_classes x 1,但是您希望将这两者相乘为 batcH_size x num_classes

    您可以试试output = tf.reshape(output, [batch_size, num_hidden])weight = tf.Variable(tf.random_normal([num_hidden, num_classes])) 并告诉我这是怎么回事吗?

    【讨论】:

    • 感谢您的回复。我仍然不太确定 RNN 输出的形状应该是什么。我尝试按照您的建议将其重塑为 [batch_size, num_hidden] 和权重为 [num_hidden, num_classes 但我收到一条错误消息-
    • `ValueError: 尺寸 10 和 5 不兼容`
    • 现在 RNN 输出的形状为 Tensor("Reshape_1:0", shape=(5, 10), dtype=float32) 但权重矩阵的形状为 Tensor("Shape:0", shape=(2,), dtype=int32)
    • 所以当你将权重矩阵初始化为eight = tf.Variable(tf.random_normal([num_hidden, num_classes]))?
    【解决方案2】:

    如果您使用的是 TF >= 1.0,则可以利用 tf.contrib.rnn 库和 OutputProjectionWrapper 将全连接层添加到 RNN 的输出中。比如:

    # Network definition.
    cell = tf.contrib.rnn.LSTMCell(num_hidden)
    cell = tf.contrib.rnn.OutputProjectionWrapper(cell, num_classes)  # adds an output FC layer for you
    output, state = tf.nn.dynamic_rnn(cell, data, dtype=tf.float32)
    
    # Training.
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=targets)
    cross_entropy = tf.reduce_sum(cross_entropy)
    optimizer = tf.train.AdamOptimizer()
    minimize = optimizer.minimize(cross_entropy)
    

    请注意,我使用的是 softmax_cross_entropy_with_logits,而不是使用您的 prediction 操作并手动计算交叉熵。它应该更高效、更健壮。

    OutputProjectionWrapper 基本上做同样的事情,但它可能有助于缓解一些头痛。

    【讨论】:

      猜你喜欢
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      • 2022-07-16
      • 2021-12-29
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多