1. tf.gather
import tensorflow as tf
# tf.gather适合索引没有规则的场合
# 以班级成绩册为例,共有4个班,每班35个同学,8门成绩
x = tf.random.uniform([4,35,8],minval=0,maxval=100,dtype=tf.int32)
# 收集第1,2班级的成绩册
tf.gather(x,[0,1],axis=0)
# 收集所有班级第1,4,18,32号同学的成绩
tf.gather(x,[0,3,17,31],axis=1)
# 收集所有同学第3,5科的成绩
tf.gather(x,[2,4],axis=2)
# 收集第2,3班级的第3,6.18号同学的5,8科目成绩,通过多个tf.gather组合实现
x1 = tf.gather(x,[1,2],axis=0)
x2 = tf.gather(x1,[2,5,17],axis=1)
x3 = tf.gather(x2,[4,7],axis=2)
2. tf.gather_nd
import tensorflow as tf
# tf.gather_nd通过指定每次采样的座标实现采样多个点的目的
# 以班级成绩册为例,共有4个班,每班35个同学,8门成绩
x = tf.random.uniform([4,35,8],minval=0,maxval=100,dtype=tf.int32)
# 收集第2个班级第3个同学的所有科目,第3个班级第4同学的成绩,第4个班级的第5个同学的成绩
tf.gather_nd(x,[[1,2],[2,3],[3,4]])
# 收集第2个班级第3个同学的第5科目,第3个班级第4同学的第5科目成绩,第4个班级的第5个同学的第5科目成绩
tf.gather_nd(x,[[1,2,4],[2,3,4],[3,4,4]])
3.tf.meshgrid
import tensorflow as tf
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# tf.meshgrid生成网格坐标
x = tf.linspace(-8.,8.,5) #设置x坐标的间隔
'''输出
[-8. -4. 0. 4. 8.]'''
print(x.numpy())
y = tf.linspace(-8.,8.,3) #设置y坐标的间隔
'''输出
[-8. 0. 8.]'''
x,y = tf.meshgrid(x,y)
'''输出
[[-8. -4. 0. 4. 8.]
[-8. -4. 0. 4. 8.]
[-8. -4. 0. 4. 8.]]
[[-8. -8. -8. -8. -8.]
[ 0. 0. 0. 0. 0.]
[ 8. 8. 8. 8. 8.]]
'''
z = x**2+y**2
'''输出
[[128. 80. 64. 80. 128.]
[ 64. 16. 0. 16. 64.]
[128. 80. 64. 80. 128.]]
'''
fig = plt.figure()
ax = Axes3D(fig)
ax.contour3D(x.numpy(), y.numpy(), z.numpy(), 50)
plt.show()