尝试共享变量basic_rnn_cell / weights,但指定了形状错误

时间:2017-03-07 09:38:33

标签: python tensorflow recurrent-neural-network

我试图在张量流中从头开始编码和学习RNN。我已经明白我们需要创建一个basicRNNCell并将其称为具有正确尺寸的rnn(数据,输入)。但是我收到尺寸错误,如下所示

这是我写的代码。

x = tf.placeholder(dtype=tf.float32, shape=[2, 4]) # Batchsize: 2, stepsize: 4
rnn = tf.contrib.rnn.BasicRNNCell(10, reuse=True)
state = rnn.zero_state(2, dtype=tf.float32) # A matrix of shape [2, 10]
rnn(x, state) # ERROR OCCURS AT THIS LINE

with tf.Session() as sess:
  sess.run(y, feed_dict={x: [[1, 2, 1, 1], [0, 0, 0, 1]]})

这是错误

  

ValueError:尝试共享变量basic_rnn_cell / weights,但指定形状(14,10)并找到形状(6,4)。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

我认为您的参数出错了。我将在这里为您报告一个有效的代码:

import tensorflow as tf
batch_size = 2
seq_len = 4
rnn_output_dim = 10

sess = tf.InteractiveSession()
x = tf.placeholder(dtype=tf.float32, shape=(batch_size, seq_len))
rnn_cell = tf.contrib.rnn.BasicRNNCell(rnn_output_dim)
state = rnn_cell.zero_state(batch_size, dtype=tf.float32)
output, state = rnn_cell(x, state)

sess.run(tf.global_variables_initializer())

res = sess.run(output, {x: [[1,2,1,1],[0,0,0,1]]})

print(res)
"""
array([[ 0.21117647, -0.66317081,  0.89524043, -0.54004282, -0.80074871,
         0.86230665, -0.77558851,  0.46061009,  0.09429809,  0.17166322],
       [ 0.42703518, -0.18116307,  0.32701704,  0.02224555, -0.39941645,
         0.10977989, -0.15780419,  0.41289148,  0.35284221, -0.21626833]], dtype=float32)
"""