進階運算

Python 的 TensorFlow 入門

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

進階運算總覽

  • 我們已經在 TensorFlow 涵蓋基本運算
    • add()multiply()matmul()reduce_sum()
  • 本課要探索進階運算
    • gradient()reshape()random()
Python 的 TensorFlow 入門

進階運算總覽

Operation Use
gradient() 計算函式在某點的斜率
reshape() 變更張量形狀(例如 10x10 成 100x1)
random() 依機率分佈產生並填入張量元素
Python 的 TensorFlow 入門

尋找最佳點

  • 在許多問題中,我們想找到函式的最佳點。

    • 極小值:損失函式的最低值。
    • 極大值:目標函式的最高值。
  • 可用 gradient() 來達成。

    • 最佳點:尋找梯度 = 0 的點。
    • 極小值:梯度變化 > 0
    • 極大值:梯度變化 < 0
Python 的 TensorFlow 入門

計算梯度

此投影片顯示函式 y 等於 x 的折線圖。

Python 的 TensorFlow 入門

計算梯度

此投影片顯示函式 y 等於 x 平方的圖。

Python 的 TensorFlow 入門

TensorFlow 中的梯度

# Import tensorflow under the alias tf
import tensorflow as tf

# Define x
x = tf.Variable(-1.0)
# Define y within instance of GradientTape
with tf.GradientTape() as tape:
    tape.watch(x)
    y = tf.multiply(x, x)
# Evaluate the gradient of y at x = -1
g = tape.gradient(y, x)
print(g.numpy())
-2.0
Python 的 TensorFlow 入門

影像作為張量

此投影片示範兩隻貓的影像可用二維張量表示,並可重塑為一維向量。

Python 的 TensorFlow 入門

如何重塑灰階影像

# Import tensorflow as alias tf
import tensorflow as tf

# Generate grayscale image
gray = tf.random.uniform([2, 2], maxval=255, dtype='int32')

# Reshape grayscale image
gray = tf.reshape(gray, [2*2, 1])

此圖示 2x2 的灰階影像被重塑為 4x1 向量。

Python 的 TensorFlow 入門

如何重塑彩色影像

# Import tensorflow as alias tf
import tensorflow as tf

# Generate color image
color = tf.random.uniform([2, 2, 3], maxval=255, dtype='int32')

# Reshape color image
color = tf.reshape(color, [2*2, 3])

此圖示 2x2x3 的彩色影像被重塑為 2x3 矩陣。

Python 的 TensorFlow 入門

一起來練習吧!

Python 的 TensorFlow 入門

Preparing Video For Download...