目录
函数定义
tensorflow中的tile()函数是用来对张量(Tensor)进行扩展的,其特点是对当前张量内的数据进行一定规则的复制。最终的输出张量维度不变。
函数定义:
tf.tile(
input,
multiples,
name=None
)
input是待扩展的张量,multiples是扩展方法,扩展后的维数不变。
假如input是一个3维的张量。那么mutiples就必须是一个1x3的1维张量。这个张量的三个值依次表示input的第1,第2,第3维数据扩展几倍。
实例
import tensorflow as tf
a = tf.constant([[1, 2], [3, 4], [5, 6]], dtype=tf.float32)
a1 = tf.tile(a, [2, 3])
with tf.Session() as sess:
print(sess.run(a))
print(sess.run(tf.shape(a)))
print(sess.run(a1))
print(sess.run(tf.shape(a1)))
=======
[[1. 2.]
[3. 4.]
[5. 6.]]
[3 2]
[[1. 2. 1. 2. 1. 2.]
[3. 4. 3. 4. 3. 4.]
[5. 6. 5. 6. 5. 6.]
[1. 2. 1. 2. 1. 2.]
[3. 4. 3. 4. 3. 4.]
[5. 6. 5. 6. 5. 6.]]
[6 6]
tf.tile()具体的操作过程如下:
(原始矩阵应为3*2)
请注意:上面绘图中第一次扩展后第一维由三个数据变成两行六个数据,多一行并不是多了一维,数据扔为顺序排列,只是为了方便绘制而已。
每一维数据的扩展都是将前面的数据进行复制然后直接接在原数据后面。
如果multiples的某一个数据为1,则表示该维数据保持不变。
在深度学习目标检测中,经常遇到需要对原始图像尺寸进行扩维的代码,理解如下:
import tensorflow as tf
# a=tf.range(10, dtype=tf.int32)
output_size=5
a=tf.range(output_size, dtype=tf.int32)#生成一个一维数组
b=tf.range(output_size, dtype=tf.int32)[tf.newaxis, :]#给数组增加一维,变为二维
c = tf.tile(tf.range(output_size, dtype=tf.int32)[tf.newaxis, :], [output_size, 1])#第一个维度复制,第二个维度不变
b1=y = tf.range(output_size, dtype=tf.int32)[:, tf.newaxis]
c1 = tf.tile(tf.range(output_size, dtype=tf.int32)[:, tf.newaxis], [1, output_size])
with tf.Session() as sess:
sess.run([a,b,c,b1,c1])
print(a,b,c,b1,c1)
Tensor("range_11:0", shape=(5,), dtype=int32) Tensor("strided_slice_3:0", shape=(1, 5), dtype=int32) Tensor("Tile_2:0", shape=(5, 5), dtype=int32) Tensor("strided_slice_5:0", shape=(5, 1), dtype=int32) Tensor("Tile_3:0", shape=(5, 5), dtype=int32)