TensorFlow – 如何广播参数以在 ND 网格上进行评估
TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
在使用 TensorFlow 时,一些操作会自动广播参数,有时我们必须显式地广播参数。使用网格网格方法显式广播参数。
Method Used:
- meshgrid: This method is used to broadcasts parameters for evaluation on an N-D grid. It accepts rank-1 tensors and broadcast all of them to same shape and returns a list of N Tensors with rank N. Default indexing for this method is ‘xy’.
示例 1:在此方法中使用默认索引。
Python3
# 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)
Python3
# 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 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”。
Python3
# 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)