Performing element-wise multiplication
Element-wise multiplication in TensorFlow is performed using two tensors with identical shapes. This is because the operation multiplies elements in corresponding positions in the two tensors. An example of an element-wise multiplication, denoted by the \(\odot\) symbol, is shown below:
\(\begin{bmatrix} 1 & 2 \\ 2 & 1 \end{bmatrix} \odot \begin{bmatrix} 3 & 1 \\ 2 & 5 \end{bmatrix} = \begin{bmatrix} 3 & 2 \\ 4 & 5 \end{bmatrix}\)
In this exercise, you will perform element-wise multiplication, paying careful attention to the shape of the tensors you multiply. Note that multiply()
, constant()
, and ones_like()
have been imported for you.
This exercise is part of the course
Introduction to TensorFlow in Python
Exercise instructions
- Define the tensors
A1
andA23
as constants. - Set
B1
to be a tensor of ones with the same shape asA1
. - Set
B23
to be a tensor of ones with the same shape asA23
. - Set
C1
andC23
equal to the element-wise products ofA1
andB1
, andA23
andB23
, respectively.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define tensors A1 and A23 as constants
A1 = ____([1, 2, 3, 4])
A23 = ____([[1, 2, 3], [1, 6, 4]])
# Define B1 and B23 to have the correct shape
B1 = ones_like(____)
B23 = ____
# Perform element-wise multiplication
C1 = ____
C23 = ____
# Print the tensors C1 and C23
print('\n C1: {}'.format(C1.numpy()))
print('\n C23: {}'.format(C23.numpy()))