TensorFlow:使用 ``tf.meshgrid`` 在 N-D 网格上广播参数进行评估


发布日期 : 2024-04-09 21:07:35 UTC

访问量: 9 次浏览

TensorFlow – 如何在N-D网格上广播参数进行评估

TensorFlow是谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

在使用TensorFlow的过程中,有些操作会自动广播参数,有时我们必须明确地广播参数。
为了明确地广播参数,我们使用了Meshgrid方法。

使用的方法:

  • meshgrid :该方法用于在N-D网格上广播参数的评估。它接受等级为1的张量,并将它们全部广播到相同的形状,并返回一个等级为N的张量列表。

例子1:
在这种方法中,使用了默认的索引。

# importing the library
import tensorflow as tf

# Initializing Input
x = [1, 2, 3]
y = [4, 5, 6, 7]

# Printing the Input
print("x: ", x)
print("y: ", y)

# Broadcasting the Tensors
X, Y = tf.meshgrid(x, y)

# Printing the resulting Tensors
print("X: ", X)
print("Y: ", Y)

输出:

x: [1, 2, 3]
y: [4, 5, 6, 7]
X: tf.Tensor(
[[1 2 3]
[1 2 3]
[1 2 3]
[1 2 3]], shape=(4, 3), dtype=int32)
Y: tf.Tensor(
[[4 4 4]
[5 5 5]
[6 6 6]
[7 7 7]], shape=(4, 3), dtype=int32)

例子2:
在这个例子中,索引被改成了’ij’。

# importing the library
import tensorflow as tf

# Initializing Input
x = [1, 2, 3]
y = [4, 5, 6, 7]

# Printing the Input
print("x: ", x)
print("y: ", y)

# Broadcasting the Tensors
X, Y = tf.meshgrid(x, y, indexing = 'ij')

# Printing the resulting Tensors
print("X: ", X)
print("Y: ", Y)

输出:

x: [1, 2, 3]
y: [4, 5, 6, 7]
X: tf.Tensor(
[[1 1 1 1]
[2 2 2 2]
[3 3 3 3]], shape=(3, 4), dtype=int32)
Y: tf.Tensor(
[[4 5 6 7]
[4 5 6 7]
[4 5 6 7]], shape=(3, 4), dtype=int32)