批次訓練

Python 的 TensorFlow 入門

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

什麼是批次訓練?

此圖顯示 King County 房屋的價格、坪數與臥室數資料。

此圖顯示將 King County 房屋的價格、坪數與臥室數資料切成多個批次。

Python 的 TensorFlow 入門

`chunksize` 參數

  • pd.read_csv() 可分批載入資料
    • 避免一次載入整個資料集
    • chunksize 參數用來設定批次大小
# Import pandas and numpy
import pandas as pd
import numpy as np

# Load data in batches
for batch in pd.read_csv('kc_housing.csv', chunksize=100):
    # Extract price column
    price = np.array(batch['price'], np.float32)

    # Extract size column
    size = np.array(batch['size'], np.float32)
Python 的 TensorFlow 入門

以批次訓練線性模型

# Import tensorflow, pandas, and numpy
import tensorflow as tf
import pandas as pd
import numpy as np
# Define trainable variables
intercept = tf.Variable(0.1, tf.float32)
slope = tf.Variable(0.1, tf.float32)
# Define the model
def linear_regression(intercept, slope, features):
    return intercept + features*slope
Python 的 TensorFlow 入門

以批次訓練線性模型

# Compute predicted values and return loss function
def loss_function(intercept, slope, targets, features):
    predictions = linear_regression(intercept, slope, features)
    return tf.keras.losses.mse(targets, predictions)
# Define optimization operation
opt = tf.keras.optimizers.Adam()
Python 的 TensorFlow 入門

以批次訓練線性模型

# Load the data in batches from pandas
for batch in pd.read_csv('kc_housing.csv', chunksize=100):
    # Extract the target and feature columns
    price_batch = np.array(batch['price'], np.float32)
    size_batch = np.array(batch['lot_size'], np.float32)

    # Minimize the loss function
    opt.minimize(lambda: loss_function(intercept, slope, price_batch, size_batch), 
                 var_list=[intercept, slope])
# Print parameter values
print(intercept.numpy(), slope.numpy())
Python 的 TensorFlow 入門

全量樣本 vs. 批次訓練

  • 全量樣本
    1. 每個 epoch 更新 1 次
    2. 可直接使用原始資料集
    3. 受記憶體限制
  • 批次訓練
    1. 每個 epoch 多次更新
    2. 需要將資料集切分
    3. 資料集大小不受限
Python 的 TensorFlow 入門

一起來練習吧!

Python 的 TensorFlow 入門

Preparing Video For Download...