Tensorflow LSTM:ValueError:Shape的等级必须至少为3

时间:2018-04-29 15:13:57

标签: python python-3.x tensorflow lstm rnn

如何使用tf.unstack将输入提供给张量流中的LSTM rnn:

因此,如果我的输入形状是[4,5,2] [batch_size , time_stamp , n_input]

现在,如果我尝试:

dataet=[[[3, 5], [7, 2], [7, 6]],
        [[2, 5], [1, 3], [4, 3]],
        [[8, 1], [1, 8], [9, 3]],
        [[1, 5], [6, 7], [4, 9]]]



import tensorflow as tf
from tensorflow.contrib import rnn
import numpy as np


input_x=tf.placeholder(dtype=tf.int32,shape=[4,3,2])
input_x=tf.cast(input_x,tf.float32)





data=tf.unstack(input_x,3,axis=1)


with tf.variable_scope('encoder') as scope:
    cell=rnn.LSTMCell(num_units=250)
    model=tf.nn.bidirectional_dynamic_rnn(cell,cell,inputs=data,dtype=tf.float32)

output,(fs,fc)=model







with tf.Session() as sess:
    unstack_output,output_n=sess.run([output,data],feed_dict={input_x:dataet})
    print(unstack_output,output_n)

我收到错误:

/anaconda/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: compiletime version 3.6 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.5
  return f(*args, **kwds)
Traceback (most recent call last):
  File "/Users/exepaul/Desktop/limit_exceed/nad.py", line 25, in <module>
    model=tf.nn.bidirectional_dynamic_rnn(cell,cell,inputs=data,dtype=tf.float32)
  File "/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/rnn.py", line 416, in bidirectional_dynamic_rnn
    time_major=time_major, scope=fw_scope)
  File "/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/rnn.py", line 632, in dynamic_rnn
    dtype=dtype)
  File "/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/rnn.py", line 695, in _dynamic_rnn_loop
    for input_ in flat_input)
  File "/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/rnn.py", line 695, in <genexpr>
    for input_ in flat_input)
  File "/anaconda/lib/python3.5/site-packages/tensorflow/python/framework/tensor_shape.py", line 673, in with_rank_at_least
    raise ValueError("Shape %s must have rank at least %d" % (self, rank))
ValueError: Shape (2, 4) must have rank at least 3

如何在tf.unstack后对RNN的输入进行整形?

我尝试检查this,但没有答案

我的设置

Tensorflow :  1.6.0

Python 3.5.4 |Anaconda custom (x86_64)|

Osx 10.12.4

1 个答案:

答案 0 :(得分:1)

为什么要对输入数据进行unstack

对于[batch_size, max_time, n_input](默认),RNN的输入应为time_major == False的张量,[max_time, batch_size, n_input]time_major == True

只需传递输入而不需要unstack操作即可。