简体   繁体   中英

Tensorflow RNN how to create zero state with various batch size?

In this question How do I set TensorFlow RNN state when state_is_tuple=True? : the accepted answer initialize the initial state like this:

state_placeholder = tf.placeholder(tf.float32, [num_layers, 2, batch_size, state_size])

I assume this requires a specific batch size, while what I have now is:

inputSeq = tf.placeholder(tf.float32, [None, seqLength, observationDim], name='input_seq')
outputs, final_state = tf.nn.dynamic_rnn(cell, inputSeq, initial_state=initialState)

And I want this initialState to be a zero state, and can be configurable as the batch size of inputSeq could vary. However, cell.zero_state does not accept None as batch size. Is there any workaround?

cell.zero_state accepts a scalar tensor.

Get the batch size of the place holder via tf.shape , then it is done: B = tf.shape(state_placeholder)[0] # the batch size scalar tensor initial_state = cell.zero_state(B)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM