我有一个1D张量a我想要堆叠/打包/平铺成像y=[a, a, a]
这样的2D张量。如果我知道我想重复多少次,我可以使用tf.tile
和reshape
。
但我不是因为尺寸取决于批量大小。占位符值为None
,它不是有效输入。我知道tf.slice
可以输入-1
并让张量流出来,但我不知道张量流如何推断出正确的大小。我确实有一个张量x
,其形状与y
相同,但我没有看到tile_like
函数。
有什么建议吗?
答案 0 :(得分:13)
您可以使用tf.shape
找出张量的运行时形状,并将其用作tf.tile
参数的基础:
import tensorflow as tf
import numpy as np
x = tf.placeholder(tf.float32, shape=[None, 3])
y = tf.tile([2, 3], tf.shape(x)[0:1])
sess = tf.Session()
print(sess.run(y, feed_dict={x: np.zeros([11, 3])}))
我验证了此代码适用于Tensorflow 1.0发布候选版。希望有所帮助!
答案 1 :(得分:0)
谢谢@Peter Hawkins的出色回答。在许多情况下,需要额外的整形步骤以将batch_size添加为第一维。我添加了一个可选的额外步骤来调整张量:
import tensorflow as tf
import numpy as np
batch_dependent_tensor = tf.placeholder(tf.float32, shape=[None, 3])
other_tensor = tf.constant([2, 3])
y = tf.tile(other_tensor, tf.shape(batch_dependent_tensor)[0:1])
# Reshaping the y tensor by adding the batch_size as the first dimension
new_shape = tf.concat([tf.shape(batch_dependent_tensor)[0:1], tf.shape(other_tensor)[0:1]], axis=0)
y_reshaped = tf.reshape(y, new_shape)
sess = tf.Session()
y_val, y_reshaped_val = sess.run([y, y_reshaped], feed_dict={batch_dependent_tensor: np.zeros([11, 3])})
print("y_val has shape %s, and value: %s" %(y_val.shape, y_val))
print("y_reshaped_val has shape %s, and value: %s" %(y_reshaped_val.shape, y_reshaped_val))
"""
# print output:
y_val has shape (22,), and value: [2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3]
y_reshaped_val has shape (11, 2), and value: [[2 3]
[2 3]
[2 3]
[2 3]
[2 3]
[2 3]
[2 3]
[2 3]
[2 3]
[2 3]
[2 3]]
"""
请注意,如果other_tensor的等级大于1(它是矩阵或具有较大维的张量),则需要对代码进行一些修改。