涉及随机数以及类RNN的网络构建常常需要根据输入shape,决定中间变量的shape或步长。 tf.shape
函数不同于tensor.shape.as_list()
函数,后者返回的是常值list,而前者返回的是tensor。使用tf.shape
函数可以使得中间变量的tensor形状随输入变化,不需要在构建Graph的时候指定。但对于tf.Variable
,因为需要提前分配固定空间,其shape无法通过上诉方法设定。
实例代码如下:
a = tf.placeholder(tf.float32,[None,]) b = tf.random_normal(tf.concat([tf.shape(a),[2,]],axis=0))