广播(broadcast_to)
利用把broadcast_to可以将小维度推广到大维度。
tf.broadcast_to(input,shape,name=None):
input:输入张量;
shape:输出张量的尺寸。
代码:
broadcast_sample_1 = tf.constant([1,2,3,4,5,6])
print("原始数据:",broadcast_sample_1.numpy())
broadcasted_sample_1 = tf.broadcast_to(broadcast_sample_1,shape=[4,6])
print("广播后数据:",broadcasted_sample_1.numpy())
输出:
原始数据: [1 2 3 4 5 6]
广播后数据: [[1 2 3 4 5 6]
[1 2 3 4 5 6]
[1 2 3 4 5 6]
[1 2 3 4 5 6]]
代码:
运算时,当两个数组的形状不同时,与numpyy一样,TensorFlow将自动触发广播机制。
a = tf.constant([[ 0, 0, 0],
[10,10,10],
[20,20,20],
[30,30,30]])
b = tf.constant([1,2,3])
print(a + b)
输出:
tf.Tensor(
[[ 1 2 3]
[11 12 13]
[21 22 23]
[31 32 33]], shape=(4, 3), dtype=int32)