1、创建一个Tensor
a = tf.random.normal([3,3])
[[ 0.27786183 -0.4933894 0.40996674]
[-0.58238053 0.12458259 1.265015 ]
[-0.51049304 -1.1052276 1.0958437 ]], shape=(3, 3), dtype=float32)
2、创建布尔Tensor
mask = a>0
[[ True False True]
[False True True]
[False False True]], shape=(3, 3), dtype=bool)
3、通过boolean_mask提取True位置的值
print(tf.boolean_mask(a,mask))
tf.Tensor([0.27786183 0.40996674 0.12458259 1.265015 1.0958437 ], shape=(5,), dtype=float32)
4、获得True的坐标
indices = tf.where(mask)
获取相应位置的数据形成新的tensor
a = tf.random.normal([3,3])
mask = a>0
print(mask)
a =tf.zeros([3,3])
b = tf.ones([3,3])
print(a)
print(b)
print(tf.where(mask,a,b))
5、获取相应坐标值
print(tf.gather_nd(a, indices))
tf.Tensor([0.27786183 0.40996674 0.12458259 1.265015 1.0958437 ], shape=(5,), dtype=float32)
6、按坐标更新数据scatter_nd,按高阶替代
indices = tf.constant([[4], [3], [1], [7]])#设定坐标
updates = tf.constant([9, 10, 11, 12])#设定数值
shape = tf.constant([8])#创建原数据
print(tf.scatter_nd(indices, updates, shape))#更新数据
7、meshgrid
生成平面均点
y = tf.linspace(-2., 2, 5) #生成-2到2五个数的值
x = tf.linspace(-2., 2, 5)
print(y,x)
points_x, points_y = tf.meshgrid(x, y) #按橫行,纵行生成5*5的点
print(points_x, points_y)