Batch training

TensorFlow เบื้องต้นใน Python

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

Batch training คืออะไร?

ภาพแสดงข้อมูลราคา ขนาด และจำนวนห้องนอนของบ้านใน King County

ภาพแสดงข้อมูลราคา ขนาด และจำนวนห้องนอนของบ้านใน King County ที่แบ่งออกเป็น batch

TensorFlow เบื้องต้นใน Python

พารามิเตอร์ chunksize

  • pd.read_csv() ช่วยโหลดข้อมูลเป็น batch
    • หลีกเลี่ยงการโหลดชุดข้อมูลทั้งหมดพร้อมกัน
    • พารามิเตอร์ chunksize กำหนดขนาดของ batch
# 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)
TensorFlow เบื้องต้นใน Python

การเทรนโมเดลเชิงเส้นแบบ batch

# 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
TensorFlow เบื้องต้นใน Python

การเทรนโมเดลเชิงเส้นแบบ batch

# 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()
TensorFlow เบื้องต้นใน Python

การเทรนโมเดลเชิงเส้นแบบ batch

# 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())
TensorFlow เบื้องต้นใน Python

Full sample เทียบกับ batch training

  • Full Sample
    1. อัปเดตครั้งเดียวต่อ epoch
    2. ใช้ชุดข้อมูลได้โดยไม่ต้องแบ่ง
    3. จำกัดด้วยหน่วยความจำ
  • Batch Training
    1. อัปเดตหลายครั้งต่อ epoch
    2. ต้องแบ่งชุดข้อมูลก่อน
    3. ไม่จำกัดขนาดชุดข้อมูล
TensorFlow เบื้องต้นใน Python

มาฝึกกันเถอะ!

TensorFlow เบื้องต้นใน Python

Preparing Video For Download...