Related Articles
TensorFlow – How to broadcasts parameters for evaluation on an N-D grid
• Last Updated : 01 Aug, 2020

TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.

While working with TensorFlow some operations automatically broadcast parameters and some times we have to explicitly broadcast parameters. To explicitly broadcast parameters meshgrid method is used.

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’.

Example 1: In this method default indexing is used.

## 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)`

Output:

```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)

```

Example 2: In this example indexing is changed to ‘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)`

Output:

```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)

```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up