常數與變數

Python 的 TensorFlow 入門

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

什麼是 TensorFlow?

  • 以圖為本的數值運算開源函式庫
    • 由 Google Brain Team 開發
  • 高階與低階 API
    • 加法、乘法、微分
    • 機器學習模型
  • TensorFlow 2.0 重要變更
    • 預設啟用 eager execution
    • 以 Keras 與 Estimators 建模
Python 的 TensorFlow 入門

什麼是張量?

  • 向量與矩陣的推廣
  • 數字的集合
  • 具特定形狀
Python 的 TensorFlow 入門

什麼是張量?

圖片顯示一片吐司、切成 9 塊的吐司片,以及一條吐司。 來源:Public Domain Vectors

Python 的 TensorFlow 入門

在 TensorFlow 中定義張量

import tensorflow as tf

# 0D Tensor
d0 = tf.ones((1,))
# 1D Tensor
d1 = tf.ones((2,))
# 2D Tensor
d2 = tf.ones((2, 2))
# 3D Tensor
d3 = tf.ones((2, 2, 2))
Python 的 TensorFlow 入門

在 TensorFlow 中定義張量

# Print the 3D tensor
print(d3.numpy())
[[[1. 1.]
  [1. 1.]]

 [[1. 1.]
  [1. 1.]]]
Python 的 TensorFlow 入門

在 TensorFlow 中定義常數

  • 常數是最簡單的張量類型
    • 不可訓練
    • 維度不限
from tensorflow import constant

# Define a 2x3 constant.
a = constant(3, shape=[2, 3])
# Define a 2x2 constant.
b = constant([1, 2, 3, 4], shape=[2, 2])
Python 的 TensorFlow 入門

用便捷函式定義常數

Operation Example
tf.constant() constant([1, 2, 3])
tf.zeros() zeros([2, 2])
tf.zeros_like() zeros_like(input_tensor)
tf.ones() ones([2, 2])
tf.ones_like() ones_like(input_tensor)
tf.fill() fill([3, 3], 7)
Python 的 TensorFlow 入門

定義與初始化變數

import tensorflow as tf

# Define a variable
a0 = tf.Variable([1, 2, 3, 4, 5, 6], dtype=tf.float32)
a1 = tf.Variable([1, 2, 3, 4, 5, 6], dtype=tf.int16)
# Define a constant
b = tf.constant(2, tf.float32)
# Compute their product
c0 = tf.multiply(a0, b)
c1 = a0*b
Python 的 TensorFlow 入門

一起來練習吧!

Python 的 TensorFlow 入門

Preparing Video For Download...