批量训练

Python 中的 TensorFlow 入门

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

什么是批量训练?

此图展示了金县房屋的价格、面积和卧室数数据。

此图展示了按批次划分的金县房屋价格、面积和卧室数数据。

Python 中的 TensorFlow 入门

chunksize 参数

  • pd.read_csv() 可分批加载数据
    • 避免一次性加载全量数据
    • chunksize 参数指定批大小
# 导入 pandas 和 numpy
import pandas as pd
import numpy as np

# 分批加载数据
for batch in pd.read_csv('kc_housing.csv', chunksize=100):
    # 提取价格列
    price = np.array(batch['price'], np.float32)

    # 提取面积列
    size = np.array(batch['size'], np.float32)
Python 中的 TensorFlow 入门

分批训练线性模型

# 导入 tensorflow、pandas 和 numpy
import tensorflow as tf
import pandas as pd
import numpy as np
# 定义可训练变量
intercept = tf.Variable(0.1, tf.float32)
slope = tf.Variable(0.1, tf.float32)
# 定义模型
def linear_regression(intercept, slope, features):
    return intercept + features*slope
Python 中的 TensorFlow 入门

分批训练线性模型

# 计算预测值并返回损失
def loss_function(intercept, slope, targets, features):
    predictions = linear_regression(intercept, slope, features)
    return tf.keras.losses.mse(targets, predictions)
# 定义优化器
opt = tf.keras.optimizers.Adam()
Python 中的 TensorFlow 入门

分批训练线性模型

# 从 pandas 分批加载数据
for batch in pd.read_csv('kc_housing.csv', chunksize=100):
    # 提取目标列与特征列
    price_batch = np.array(batch['price'], np.float32)
    size_batch = np.array(batch['lot_size'], np.float32)

    # 最小化损失函数
    opt.minimize(lambda: loss_function(intercept, slope, price_batch, size_batch), 
                 var_list=[intercept, slope])
# 打印参数值
print(intercept.numpy(), slope.numpy())
Python 中的 TensorFlow 入门

全量样本 vs 批量训练

  • 全量样本
    1. 每个 epoch 一次更新
    2. 可直接使用数据集
    3. 受内存限制
  • 批量训练
    1. 每个 epoch 多次更新
    2. 需将数据集拆分
    3. 数据规模不受限
Python 中的 TensorFlow 入门

开始练习吧!

Python 中的 TensorFlow 入门

Preparing Video For Download...