基本运算

Python 中的 TensorFlow 入门

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

什么是 TensorFlow 操作?

图像显示由 TensorBoard 绘制的 TensorFlow 计算图中的操作与张量。两对矩阵通过 add 操作相加,所得和再相乘。

Python 中的 TensorFlow 入门

什么是 TensorFlow 操作?

图像显示由 TensorBoard 绘制的 TensorFlow 计算图中的操作与张量。展示一次 add 操作。

Python 中的 TensorFlow 入门

什么是 TensorFlow 操作?

图像显示由 TensorBoard 绘制的 TensorFlow 计算图中的操作与张量。展示两次 add 操作。

Python 中的 TensorFlow 入门

什么是 TensorFlow 操作?

图像显示由 TensorBoard 绘制的 TensorFlow 计算图中的操作与张量。两对矩阵通过 add 操作相加,所得和再相乘。

Python 中的 TensorFlow 入门

应用加法运算符

# 从 tensorflow 导入 constant 和 add
from tensorflow import constant, add

# 定义 0 维张量
A0 = constant([1])
B0 = constant([2])
# 定义 1 维张量
A1 = constant([1, 2])
B1 = constant([3, 4])
# 定义 2 维张量
A2 = constant([[1, 2], [3, 4]])
B2 = constant([[5, 6], [7, 8]])
Python 中的 TensorFlow 入门

应用加法运算符

# 使用 add() 进行张量相加
C0 = add(A0, B0)
C1 = add(A1, B1)
C2 = add(A2, B2)
Python 中的 TensorFlow 入门

执行张量加法

  • add() 对两个张量执行按元素相加

  • 按元素相加要求两个张量形状相同:

    • 标量相加:$1+2=3$
    • 向量相加:$[1,2]+[3,4]=[4,6]$
    • 矩阵相加:$\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} + \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix} = \begin{bmatrix} 6 & 8 \\ 10 & 12 \end{bmatrix}$
  • add() 运算符已重载

Python 中的 TensorFlow 入门

在 TensorFlow 中进行乘法

  • 按元素乘法 使用 multiply()

    • 相乘张量需形状相同
    • 例如 [1,2,3] 与 [3,4,5],或 [1,2] 与 [3,4]
  • 矩阵乘法 使用 matmul()

    • matmul(A,B) 计算 A 乘以 B
    • A 的列数需等于 B 的行数
Python 中的 TensorFlow 入门

应用乘法运算符

# 从 tensorflow 导入算子
from tensorflow import ones, matmul, multiply

# 定义张量
A0 = ones(1)
A31 = ones([3, 1])
A34 = ones([3, 4])
A43 = ones([4, 3])

  • 哪些运算是有效的?
    • multiply(A0, A0)multiply(A31, A31)multiply(A34, A34)
    • 可用 matmul(A43, A34),不可用 matmul(A43, A43)
Python 中的 TensorFlow 入门

在各维度上求和

  • reduce_sum() 在张量维度上求和
    • reduce_sum(A) 对 A 的所有维度求和
    • reduce_sum(A, i) 对第 i 个维度求和
# 从 tensorflow 导入操作
from tensorflow import ones, reduce_sum

# 定义一个 2x3x4 的全 1 张量
A = ones([2, 3, 4])
Python 中的 TensorFlow 入门

在各维度上求和

# 对所有维度求和
B = reduce_sum(A)

# 分别对第 0、1、2 维求和
B0 = reduce_sum(A, 0)
B1 = reduce_sum(A, 1)
B2 = reduce_sum(A, 2)
Python 中的 TensorFlow 入门

¡Vamos a practicar!

Python 中的 TensorFlow 入门

Preparing Video For Download...