Addestramento a batch

Introduzione a TensorFlow in Python

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

Che cos'è il training a batch?

Questa immagine mostra i dati su prezzo, metratura e numero di camere da letto delle case nella King County.

Questa immagine mostra gli stessi dati su prezzo, metratura e camere da letto, suddivisi in batch.

Introduzione a TensorFlow in Python

Il parametro chunksize

  • pd.read_csv() permette di caricare i dati a batch
    • Evita di caricare l'intero insieme di dati
    • Il parametro chunksize definisce la dimensione del 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)
Introduzione a TensorFlow in Python

Addestrare un modello lineare a 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
Introduzione a TensorFlow in Python

Addestrare un modello lineare a 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()
Introduzione a TensorFlow in Python

Addestrare un modello lineare a 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())
Introduzione a TensorFlow in Python

Campione completo vs training a batch

  • Campione completo
    1. Un aggiornamento per epoca
    2. Accetta l'insieme di dati senza modifiche
    3. Limitato dalla memoria
  • Training a batch
    1. Più aggiornamenti per epoca
    2. Richiede la suddivisione dell'insieme di dati
    3. Nessun limite alla dimensione dei dati
Introduzione a TensorFlow in Python

Esercitiamoci!

Introduzione a TensorFlow in Python

Preparing Video For Download...