배치 학습

Python으로 시작하는 TensorFlow

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

배치 학습이란?

이 이미지는 킹 카운티 주택의 가격, 면적, 침실 수 데이터를 보여줍니다.

이 이미지는 킹 카운티 주택의 가격, 면적, 침실 수 데이터를 배치로 나누어 보여줍니다.

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. 에폭당 1회 업데이트
    2. 데이터셋 수정 없이 사용
    3. 메모리 제약
  • 배치 학습
    1. 에폭당 여러 번 업데이트
    2. 데이터셋 분할 필요
    3. 데이터 크기 제한 없음
Python으로 시작하는 TensorFlow

연습해 봅시다!

Python으로 시작하는 TensorFlow

Preparing Video For Download...