进阶 tensorflow.org 2026-10-22 02:47:47 · 18 阅读

第9章 TensorFlow 基础训练循环详解

TensorFlow 学习 TensorFlow Core 指南

基本训练循环

使用集合整理内容,根据您的偏好保存和分类内容。

在 TensorFlow.org 上查看 在 Google Colab 中运行 在 GitHub 上查看源码 下载 notebook

在前面的指南中,你已经学习了张量、变量、梯度带和模块。本指南将把它们全部结合起来训练模型。

TensorFlow 还包含 tf.Keras API,这是一个高级神经网络 API,提供了实用的抽象来减少样板代码。不过,本指南将使用基础类来完成。

准备工作 import tensorflow as tf

import matplotlib.pyplot as plt

colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

解决机器学习问题

解决机器学习问题通常包括以下几个步骤:

获取训练数据。 定义模型。 定义损失函数。 遍历训练数据,根据理想值计算损失。 计算损失的梯度,并使用优化器调整变量以拟合数据。 评估结果。

为了便于说明,本指南将构建一个简单的线性模型 \(f(x) = x * W + b\),它有两个变量:\(W\)(权重)和 \(b\)(偏置)。

这是最基本的机器学习问题:给定 \(x\) 和 \(y\),通过简单线性回归找到一条直线的斜率和截距。

数据

监督学习使用输入(通常记作 x)和输出(记作 y,通常称为标签)。目标是从成对的输入输出中学习,从而根据输入预测输出的值。

在 TensorFlow 中,数据的每个输入几乎总是由张量表示,且通常是向量。在监督训练中,输出(即你想预测的值)也是张量。

下面是一些合成数据:在一条直线上的点加入高斯(正态)噪声。 # The actual line TRUE_W = 3.0 TRUE_B = 2.0

NUM_EXAMPLES = 201

# A vector of random x values x = tf.linspace(-2,2, NUM_EXAMPLES) x = tf.cast(x, tf.float32)

def f(x): return x * TRUE_W + TRUE_B

# Generate some noise noise = tf.random.normal(shape=[NUM_EXAMPLES])

# Calculate y y = f(x) + noise # Plot all the data plt.plot(x, y, '.') plt.show()

张量通常以批次(batch)的形式组织,也就是把多组输入和输出堆叠在一起。分批训练能带来一些好处,并且与加速器和向量化计算配合良好。本例的数据集很小,可以把整个数据集当作一个批次处理。

定义模型

用 tf.Variable 表示模型中的所有权重。tf.Variable 存储一个值,并在需要时以张量形式提供。详见变量指南。

用 tf.Module 封装变量和计算。虽然可以用任意 Python 对象,但这样更容易保存模型。

这里把 w 和 b 都定义为变量。 class MyModel(tf.Module): def __init__(self, kwargs): super().__init__(kwargs) # Initialize the weights to `5.0` and the bias to `0.0` # In practice, these should be randomly initialized self.w = tf.Variable(5.0) self.b = tf.Variable(0.0)

def __call__(self, x): return self.w * x + self.b

model = MyModel()

# List the variables tf.modules's built-in variable aggregation. print("Variables:", model.variables)

# Verify the model works assert model(3.0).numpy() == 15.0

这里初始变量是固定设置的,但 Keras 提供了多种初始化器,可以单独使用,也可以配合 Keras 的其他功能一起使用。

定义损失函数

损失函数衡量模型对给定输入的输出与目标输出的匹配程度。训练的目标是最小化这个差异。这里定义标准的 L2 损失,也就是“均方误差”: # This computes a single loss value for an entire batch def loss(target_y, predicted_y): return tf.reduce_mean(tf.square(target_y - predicted_y))

在训练模型之前,可以先可视化损失值:把模型的预测画成红色,训练数据画成蓝色: plt.plot(x, y, '.', label="Data") plt.plot(x, f(x), label="Ground truth") plt.plot(x, model(x), label="Predictions") plt.legend() plt.show()

print("Current loss: %1.6f" % loss(y, model(x)).numpy())

定义训练循环

训练循环就是按顺序反复执行三个任务:

把一批输入送入模型生成输出。 将输出与目标输出(即标签)对比,计算损失。 使用梯度带求梯度,并用这些梯度优化变量。

本例使用梯度下降来训练模型。

梯度下降有很多变体,都包含在 tf.keras.optimizers 中。但为了从第一性原理出发,这里将借助 tf.GradientTape 进行自动微分,用 tf.assign_sub 递减值(相当于 tf.assign 与 tf.sub 的组合),自己实现基础的数学运算: # Given a callable model, inputs, outputs, and a learning rate... def train(model, x, y, learning_rate):

with tf.GradientTape() as t: # Trainable variables are automatically tracked by GradientTape current_loss = loss(y, model(x))

# Use GradientTape to calculate the gradients with respect to W and b dw, db = t.gradient(current_loss, [model.w, model.b])

# Subtract the gradient scaled by the learning rate model.w.assign_sub(learning_rate * dw) model.b.assign_sub(learning_rate * db)

为了观察训练过程,可以把同一批 x 和 y 反复送入训练循环,看看 W 和 b 如何演化。 model = MyModel()

# Collect the history of W-values and b-values to plot later weights = [] biases = [] epochs = range(10)

# Define a training loop def report(model, loss): return f"W = {model.w.numpy():1.2f}, b = {model.b.numpy():1.2f}, loss={loss:2.5f}"

def training_loop(model, x, y):

for epoch in epochs: # Update the model with the single giant batch train(model, x, y, learning_rate=0.1)

# Track this before I update weights.append(model.w.numpy()) biases.append(model.b.numpy()) current_loss = loss(y, model(x))

print(f"Epoch {epoch:2d}:") print(" ", report(model, current_loss))

开始训练: current_loss = loss(y, model(x))

print(f"Starting:") print(" ", report(model, current_loss))

training_loop(model, x, y)

绘制权重随时间的演化: plt.plot(epochs, weights, label='Weights', color=colors[0]) plt.plot(epochs, [TRUE_W] * len(epochs), '--', label = "True weight", color=colors[0])

plt.plot(epochs, biases, label='bias', color=colors[1]) plt.plot(epochs, [TRUE_B] * len(epochs), "--", label="True bias", color=colors[1])

plt.legend() plt.show()

再看看训练后的模型表现: plt.plot(x, y, '.', label="Data") plt.plot(x, f(x), label="Ground truth") plt.plot(x, model(x), label="Predictions") plt.legend() plt.show()

print("Current loss: %1.6f" % loss(model(x), y).numpy())

同样的方案,用 Keras 实现

把上面的代码与 Keras 中的等价实现对比一下会很有帮助。

如果继承 tf.keras.Model 来定义模型,代码几乎完全一样。记住 Keras 模型最终都继承自 Module。 class MyModelKeras(tf.keras.Model): def __init__(self, kwargs): super().__init__(kwargs) # Initialize the weights to `5.0` and the bias to `0.0` # In practice, these should be randomly initialized self.w = tf.Variable(5.0) self.b = tf.Variable(0.0)

def call(self, x): return self.w * x + self.b

keras_model = MyModelKeras()

# Reuse the training loop with a Keras model training_loop(keras_model, x, y)

# You can also save a checkpoint using Keras's built-in support keras_model.save_weights("my_checkpoint")

不用每次创建模型都手写训练循环,可以用 Keras 的内置功能作为捷径。当你不想编写或调试 Python 训练循环时,这很有用。

这时需要用 model.compile() 设置参数,用 model.fit() 训练。直接使用 Keras 内置的 L2 损失和梯度下降实现也能减少代码量。此外,Keras 的损失和优化器也可以在这些便捷函数之外单独使用,前面的示例本可以直接采用。 keras_model = MyModelKeras()

# compile sets the training parameters keras_model.compile( # By default, fit() uses tf.function(). You can # turn that off for debugging, but it is on now. run_eagerly=False,

# Using a built-in optimizer, configuring as an object optimizer=tf.keras.optimizers.SGD(learning_rate=0.1),

# Keras comes with built-in MSE error # However, you could use the loss function # defined above loss=tf.keras.losses.mean_squared_error, )

Keras 的 fit 期望传入分批的数据或完整的 NumPy 数组数据集。NumPy 数组会被切分成批次,默认批次大小为 32。

本例中,为了与手写的循环保持一致,应该把 x 作为一批大小为 1000 的数据传入。 print(x.shape[0]) keras_model.fit(x, y, epochs=10, batch_size=1000)

注意 Keras 打印的是训练后的损失而非训练前,所以第一个损失看起来偏低,除此之外,这里展现的训练效果与之前基本一致。

后续步骤

在本指南中,你学习了如何使用张量、变量、模块和梯度带这些核心类来构建和训练模型,以及这些概念如何映射到 Keras。

不过,这只是一个非常简单的问题。想看更实用的入门示例,请参阅自定义训练演练。

关于使用 Keras 内置训练循环的更多内容,请参阅本指南。关于训练循环与 Keras 的更多信息,请参阅本指南。关于编写自定义分布式训练循环,请参阅本指南。

评论 (0)