当相同的基本单元 (cell1, cell1) 用于 MultiRNNCell 时,以下代码失败:
import tensorflow as tf
cell1 = tf.contrib.rnn.BasicLSTMCell(128,reuse=False, name = "cell1")
cell2 = tf.contrib.rnn.BasicLSTMCell(128,reuse=False,name = "cell2")
multi = tf.contrib.rnn.MultiRNNCell([cell1, cell1] )
init = multi.zero_state(64, tf.float32)
output,state = multi(tf.ones([64,512]),init)
此代码与 (cell1, cell2) 一起工作。但是 cell2 与 cell1 相同:
import tensorflow as tf
cell1 = tf.contrib.rnn.BasicLSTMCell(128,reuse=False, name = "cell1")
cell2 = tf.contrib.rnn.BasicLSTMCell(128,reuse=False,name = "cell2")
multi = tf.contrib.rnn.MultiRNNCell([cell1, cell2] )
init = multi.zero_state(64, tf.float32)
output,state = multi(tf.ones([64,512]),init)
我可以知道这两个代码示例的区别吗?
错误是这样的:
ValueError: Dimensions must be equal, but are 256 and 640 for 'multi_rnn_cell/cell_0/cell1/MatMul_1' (op: 'MatMul') with input shapes: [64,256], [640,512].
请您参考如下方法:
这是一个已知的限制(例如讨论过的 here )。问题是每个单元格实例都会为权重创建一个内部变量。此变量的维数由隐藏大小(在您的情况下为 128)和此单元格实例接收的输入大小(512)决定。当您多次使用同一个单元格时,您必须确保所有情况下的输入都相同。
考虑您的示例代码:
import tensorflow as tf
cell1 = tf.contrib.rnn.BasicLSTMCell(128,reuse=False, name = "cell1")
cell2 = tf.contrib.rnn.BasicLSTMCell(128,reuse=False,name = "cell2")
multi = tf.contrib.rnn.MultiRNNCell([cell1, cell1] )
init = multi.zero_state(64, tf.float32)
output,state = multi(tf.ones([64,512]),init)
multi 中两个单元格的输入将是 [..., 640]和 [..., 256] ,因为 640=512+128 (该单元格接收来自前一个单元格以及输入序列的输入)。因此,它们内部的权重矩阵将是 [640, 512] 和 [256, 512] ( 512 这里其实是 128*4 ,不是输入大小)。
但是您使用的是同一个单元格实例! Tensorflow 尝试将其已有的矩阵与新输入匹配,但失败了。另一方面,当您使用不同的实例时,tensorflow 能够为不同的层实例化不同的矩阵并正确计算出形状。
