tf.meshgrid() 构建n维网格

介绍

构建n维网格

语法

tf.meshgrid(
    *args,
    **kwargs
)

例子

例子1

x = tf.range(3, dtype=tf.float32)
y = tf.range(4, dtype=tf.float32)
print(x)
print(y)

print('-'*50)
x2, y2 = tf.meshgrid(x, y)
print(x2)
print(y2)

执行结果:

tf.Tensor([0. 1. 2.], shape=(3,), dtype=float32)
tf.Tensor([0. 1. 2. 3.], shape=(4,), dtype=float32)
--------------------------------------------------
tf.Tensor(
[[0. 1. 2.]
 [0. 1. 2.]
 [0. 1. 2.]
 [0. 1. 2.]], shape=(4, 3), dtype=float32)
tf.Tensor(
[[0. 0. 0.]
 [1. 1. 1.]
 [2. 2. 2.]
 [3. 3. 3.]], shape=(4, 3), dtype=float32)

解释:
传入x,y,那么返回结果x2,y2都是二维,形状是(m,n),m是y的元素数量,n是x的元素数量
可以理解为:

  • x2 是沿着 0 轴重复了m次(m是y1的长度)
  • y2 是沿着 1 轴重复了n次(n是y1的长度)

构建网格坐标

用于目标检测

x = tf.range(3, dtype=tf.float32)
y = tf.range(3, dtype=tf.float32)
x2, y2 = tf.meshgrid(x, y)

grid = tf.stack([x2,y2],axis=-1)

print(grid)

执行结果:

tf.Tensor(
[[[0. 0.]
  [1. 0.]
  [2. 0.]]

 [[0. 1.]
  [1. 1.]
  [2. 1.]]

 [[0. 2.]
  [1. 2.]
  [2. 2.]]], shape=(3, 3, 2), dtype=float32)

更多维度,更多参数

x = tf.reshape(tf.range(8, dtype=tf.float32),[2,2,2])
y = tf.reshape(tf.range(4, dtype=tf.float32),[2,2])
z = tf.reshape(tf.range(6, dtype=tf.float32),[2,3])
# print(x)
# print(y)
# print(z)

print('-'*50)
x2, y2,z2 = tf.meshgrid(x, y,z)
print(x)
print(y)
print(z)

解释:

  1. 传入3个参数,所以结果 x2, y2,z2都是3维,形状都是(4,8,6)。4是y的元素数量,8是x的元素数量,6是z的元素数量
  2. x2的值,是将x展平,在0轴重复4次,2轴重复6次
  3. y2的值,是将y展平,每一个元素在1轴重复8次,2轴重复6次
  4. z2的值,是将z展平,在0轴重复4次,1轴重复8次

原文出处:/show_1EF5FOM7EMvN.html