1.Where
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'#过滤爆红的信息
import tensorflow as tf
a = tf.random.normal([3,3])
mask=a>0
print(mask)#得到bool
b=tf.boolean_mask(a,mask)
print(b)#将bool编译
indice=tf.where(mask)#得到坐标
print(tf.gather_nd(a,indice))
A=tf.ones([3,3])
B=tf.zeros([3,3])
print(tf.where(mask,A,B))
输出:
tf.Tensor(
[[False False True]
[False True False]
[False True False]], shape=(3, 3), dtype=bool)
tf.Tensor([0.70666766 1.02855 1.7654202 ], shape=(3,), dtype=float32)
tf.Tensor([0.70666766 1.02855 1.7654202 ], shape=(3,), dtype=float32)
tf.Tensor(
[[0. 0. 1.]
[0. 1. 0.]
[0. 1. 0.]], shape=(3, 3), dtype=float32)
2.改变某位置数值scatter_nd:
#改变位置数值
indice = tf.constant([[5],[0],[1],[3]])
updates = tf.constant([9,18,12,0])
shape = tf.constant([8])#8个0
print(tf.scatter_nd(indice,updates,shape))#先位置,再更新的数字,再加上越来的shape
输出:
tf.Tensor([18 12 0 0 0 9 0 0], shape=(8,), dtype=int32)
3.meshgrid:
y=tf.linspace(2.,-2,5)#取2到-2之间的值,5个间隔
x=tf.linspace(2.,-2,5)
point_x,point_y=tf.meshgrid(x,y)#返回切割的x,y张量
print(tf.stack([point_x,point_y]))
输出:
tf.Tensor(
[[[ 2. 1. 0. -1. -2.]
[ 2. 1. 0. -1. -2.]
[ 2. 1. 0. -1. -2.]
[ 2. 1. 0. -1. -2.]
[ 2. 1. 0. -1. -2.]]
[[ 2. 2. 2. 2. 2.]
[ 1. 1. 1. 1. 1.]
[ 0. 0. 0. 0. 0.]
[-1. -1. -1. -1. -1.]
[-2. -2. -2. -2. -2.]]], shape=(2, 5, 5), dtype=float32)