tensorflow中的算术运算(高维度)

import tensorflow as tf
import numpy as np

x = tf.ones((2, 3, 6),dtype=tf.int32)
print(x)
y = np.array([[2,5,8,7,3,2]])
y= tf.convert_to_tensor(y)
print(y)

tf.Tensor(
[[[1 1 1 1 1 1]
[1 1 1 1 1 1]
[1 1 1 1 1 1]]

[[1 1 1 1 1 1]
[1 1 1 1 1 1]
[1 1 1 1 1 1]]], shape=(2, 3, 6), dtype=int32)
tf.Tensor([[2 5 8 7 3 2]], shape=(1, 6), dtype=int32)

out = tf.subtract(x,y)

<tf.Tensor: shape=(2, 3, 6), dtype=int32, numpy=
array([[[-1, -4, -7, -6, -2, -1],
[-1, -4, -7, -6, -2, -1],
[-1, -4, -7, -6, -2, -1]],
[[-1, -4, -7, -6, -2, -1],
[-1, -4, -7, -6, -2, -1],
[-1, -4, -7, -6, -2, -1]]])>
总结:这个例子很好的说明出,广播的方式。
首先,将二维的[[2 5 8 7 3 2]]矩阵,广播成(3,6)的shape,因此:
[[2 5 8 7 3 2],
[2 5 8 7 3 2],
[2 5 8 7 3 2]]
然后再将这个矩阵广播成(2,3,6),因此:
[[[2 5 8 7 3 2],
[2 5 8 7 3 2],
[2 5 8 7 3 2]],

[[2 5 8 7 3 2],
[2 5 8 7 3 2],
[2 5 8 7 3 2]]]

Guess you like

Origin blog.csdn.net/weixin_44885180/article/details/116425000