進行逐元素相乘
在 TensorFlow 中,逐元素相乘需要使用兩個形狀相同的張量。這是因為此運算會將兩個張量中相同位置的元素相乘。下面以符號 \(\odot\) 表示的逐元素相乘範例如下:
\(\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}\)
在本練習中,你將進行逐元素相乘,並特別注意要相乘的張量形狀。注意,multiply()、constant() 和 ones_like() 已為你匯入。
本練習屬於課程
Python 的 TensorFlow 入門
練習說明
- 將張量
A1和A23定義為常數。 - 將
B1設為與A1形狀相同、元素全為 1 的張量。 - 將
B23設為與A23形狀相同、元素全為 1 的張量。 - 分別將
C1與C23設為A1與B1、以及A23與B23的逐元素乘積。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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()))