基本運算

Python 的 TensorFlow 入門

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

什麼是 TensorFlow 運算?

圖片顯示 TensorBoard 繪製的 TensorFlow 圖中運算與張量。兩對矩陣以加法運算結合,所得和再相乘。

Python 的 TensorFlow 入門

什麼是 TensorFlow 運算?

圖片顯示 TensorBoard 繪製的 TensorFlow 圖中運算與張量。展示一個加法運算。

Python 的 TensorFlow 入門

什麼是 TensorFlow 運算?

圖片顯示 TensorBoard 繪製的 TensorFlow 圖中運算與張量。展示兩個加法運算。

Python 的 TensorFlow 入門

什麼是 TensorFlow 運算?

圖片顯示 TensorBoard 繪製的 TensorFlow 圖中運算與張量。兩對矩陣以加法運算結合,所得和再相乘。

Python 的 TensorFlow 入門

套用加法運算子

#Import constant and add from tensorflow
from tensorflow import constant, add

# Define 0-dimensional tensors
A0 = constant([1])
B0 = constant([2])
# Define 1-dimensional tensors
A1 = constant([1, 2])
B1 = constant([3, 4])
# Define 2-dimensional tensors
A2 = constant([[1, 2], [3, 4]])
B2 = constant([[5, 6], [7, 8]])
Python 的 TensorFlow 入門

套用加法運算子

# Perform tensor addition with 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 入門

套用乘法運算子

# Import operators from tensorflow
from tensorflow import ones, matmul, multiply

# Define tensors
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 維求和
# Import operations from tensorflow
from tensorflow import ones, reduce_sum

# Define a 2x3x4 tensor of ones
A = ones([2, 3, 4])
Python 的 TensorFlow 入門

沿張量維度加總

# Sum over all dimensions
B = reduce_sum(A)

# Sum over dimensions 0, 1, and 2
B0 = reduce_sum(A, 0)
B1 = reduce_sum(A, 1)
B2 = reduce_sum(A, 2)
Python 的 TensorFlow 入門

一起來練習吧!

Python 的 TensorFlow 入門

Preparing Video For Download...