按元素相乘
在 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()))