python-machine-learning-book-3rd-edition:深入 TensorFlow 内部机制——计算图、Keras API 与 Estimator 实战指南(ch14)

原创2026-10-14 13:48:061,768 阅读
文章标签:示例工程教程机器学习深度学习

python-machine-learning-book-3rd-edition:深入 TensorFlow 内部机制——计算图、Keras API 与 Estimator 实战指南(ch14)

本篇指南以《Python Machine Learning(第 3 版)》第 14 章为骨架,围绕当前仓库 ch14/README.md 及其配套的 Notebook/脚本源码,系统讲解 TensorFlow 的底层计算机制(计算图、@tf.function、Variable、GradientTape)、Keras API 的多种建模方式,以及 TensorFlow Estimators 的完整工作流。读完本文,你将掌握:如何把 TensorFlow v1 风格代码迁移到 v2、如何用自动微分手动实现梯度更新、如何用 Keras 的三种范式搭建并训练模型、如何用特征列与预置/自定义 Estimator 完成回归与图像分类任务,并能直接运行仓库中的全部示例。

章节总览:第 14 章的知识地图

第 14 章 "Going Deeper – The Mechanics of TensorFlow" 的完整脉络如下,这也是本文的展开顺序:

  • TensorFlow 的核心特性
    • TensorFlow 的计算图:向 TensorFlow v2 迁移
      • 理解计算图(computation graphs)
      • 在 TensorFlow v1.x 中创建图
      • 将图迁移到 TensorFlow v2
      • 向模型加载输入数据:TensorFlow v1.x 风格
      • 向模型加载输入数据:TensorFlow v2 风格
    • 使用函数装饰器(function decorators)提升计算性能
    • 用 TensorFlow Variable 对象存储与更新模型参数
    • 通过自动微分与 GradientTape 计算梯度
      • 计算损失关于可训练变量的梯度
      • 计算关于不可训练张量的梯度
      • 为多次梯度计算保留资源(persistent=True)
  • 通过 Keras API 简化常见架构的实现
    • 解决一个 XOR 分类问题
    • 用 Keras 函数式 API(functional API)让模型构建更灵活
    • 基于 Keras Model 类实现模型
    • 编写自定义 Keras 层
  • TensorFlow Estimators
    • 使用特征列(feature columns)
    • 使用预置 Estimator 做机器学习
    • 用 Estimator 做 MNIST 手写数字分类
    • 从已有 Keras 模型创建自定义 Estimator
  • 小结(Summary)

仓库中用三份 Jupyter Notebook / Python 脚本承载了上述全部内容,后文将逐一深入。

从仓库出发:三份 Notebook / 脚本的组织方式

当前仓库的 ch14 目录下实际包含三对 Notebook 与脚本文件:

文件 覆盖主题
ch14/ch14_part1.ipynb(对应 ch14/ch14_part1.py) TensorFlow 核心特性(计算图、@tf.function、Variable、GradientTape)与 Keras API 全部建模范式
ch14/ch14_part2.ipynb(对应 ch14/ch14_part2.py) Estimators:特征列、预置回归器(DNNRegressor、BoostedTreesRegressor)
ch14/ch14_part3.ipynb(对应 ch14/ch14_part3.py) 用 Estimator 做 MNIST 分类,以及从 Keras 模型创建自定义 Estimator

说明:ch14/README.md 中直接给出的是 ch14_part1.ipynb 与 ch14_part2.ipynb 两个入口;仓库实际还补充了第三部分,三者合起来才覆盖完整章节内容。

每份 Notebook 都带有与书本一致的目录与节标题,并把书中原始图片一并嵌入,便于边读边跑。

深入 TensorFlow 核心机制:计算图与自动微分

理解计算图,并把代码迁移到 TensorFlow v2

TensorFlow v1 的核心抽象是计算图(computation graph):先用符号节点描述计算,再在 Session 中按图执行。v2 默认启用 eager 执行(动态图),计算随写随跑,无需 Session。仓库 ch14/ch14_part1.py 用同一个表达式 z = 2*(a - b) + c 展示了两种风格的差异。

TensorFlow v1.x 风格:先建图,再在 Session 中运行

g = tf.Graph()
with g.as_default():
    a = tf.constant(1, name='a')
    b = tf.constant(2, name='b')
    c = tf.constant(3, name='c')
    z = 2*(a - b) + c

with tf.compat.v1.Session(graph=g) as sess:
    print('Result: z =', sess.run(z))
    print('Result: z =', z.eval())

这里显式创建 tf.Graph,用 as_default() 把常量节点加入图,随后在 tf.compat.v1.Session 中调用 sess.run(z) 或 z.eval() 求出结果。注意在 v2 环境里调用 v1 接口需要经过 tf.compat.v1 兼容层。

TensorFlow v2 风格:eager 执行,直接计算

a = tf.constant(1, name='a')
b = tf.constant(2, name='b')
c = tf.constant(3, name='c')

z = 2*(a - b) + c
tf.print('Result: z =', z)

v2 下不再需要 Graph/Session,张量运算立即得到数值结果,可用 tf.print 直接输出——这正是"迁移到 v2"的核心简化。

加载输入数据:placeholder/feed_dict 与函数参数

TensorFlow v1.x 风格:占位符 + feed_dict

g = tf.Graph()
with g.as_default():
    a = tf.compat.v1.placeholder(shape=None, dtype=tf.int32, name='tf_a')
    b = tf.compat.v1.placeholder(shape=None, dtype=tf.int32, name='tf_b')
    c = tf.compat.v1.placeholder(shape=None, dtype=tf.int32, name='tf_c')
    z = 2*(a - b) + c

with tf.compat.v1.Session(graph=g) as sess:
    feed_dict = {a:1, b:2, c:3}
    print('Result: z =', sess.run(z, feed_dict=feed_dict))

v1 通过 placeholder 声明输入节点,运行阶段再用 feed_dict 把真实数值灌进图里。

TensorFlow v2 风格:普通 Python 函数 + 张量操作

def compute_z(a, b, c):
    r1 = tf.subtract(a, b)
    r2 = tf.multiply(2, r1)
    z = tf.add(r2, c)
    return z

tf.print('Scalar Inputs:', compute_z(1, 2, 3))
tf.print('Rank 1 Inputs:', compute_z([1], [2], [3]))
tf.print('Rank 2 Inputs:', compute_z([[1]], [[2]], [[3]]))

同样的逻辑在 v2 里就是一个普通函数,标量、一维、二维输入均可直接传入,无需占位符与会话,可读性与可调试性大幅提升。

用 @tf.function 与 input_signature 提升性能

eager 模式方便,但纯解释执行有性能开销。@tf.function 装饰器会把 Python 函数编译为计算图,兼顾易用与性能。仓库代码演示了两种用法:

基础用法:直接装饰函数

@tf.function
def compute_z(a, b, c):
    r1 = tf.subtract(a, b)
    r2 = tf.multiply(2, r1)
    z = tf.add(r2, c)
    return z

tf.print('Scalar Inputs:', compute_z(1, 2, 3))
tf.print('Rank 1 Inputs:', compute_z([1], [2], [3]))
tf.print('Rank 2 Inputs:', compute_z([[1]], [[2]], [[3]]))

进阶用法:用 input_signature 固定输入签名

@tf.function(input_signature=(tf.TensorSpec(shape=[None], dtype=tf.int32),
                              tf.TensorSpec(shape=[None], dtype=tf.int32),
                              tf.TensorSpec(shape=[None], dtype=tf.int32),))
def compute_z(a, b, c):
    r1 = tf.subtract(a, b)
    r2 = tf.multiply(2, r1)
    z = tf.add(r2, c)
    return z

tf.print('Rank 1 Inputs:', compute_z([1], [2], [3]))
tf.print('Rank 1 Inputs:', compute_z([1, 2], [2, 4], [3, 6]))

tf.TensorSpec(shape=[None], dtype=tf.int32) 声明输入是一维 int32 张量(None 表示批大小可变),从而让图只被编译一次并复用。仓库注释中特别演示了与之不匹配的输入会抛错:

# 预期会报错:
# tf.print('Rank 2 Inputs:', compute_z([[1], [2]], [[2], [4]], [[3], [6]]))
# >> ValueError: Python inputs incompatible with input_signature: ...

Variable 对象:模型参数的存储与更新

模型参数需要用可变的 tf.Variable 承载。仓库代码展示了四种初始化方式:

a = tf.Variable(initial_value=3.14, name='var_a')
b = tf.Variable(initial_value=[1, 2, 3], name='var_b')
c = tf.Variable(initial_value=[True, False], dtype=tf.bool)
d = tf.Variable(initial_value=['abc'], dtype=tf.string)

Variable 默认是可训练的(a.trainable 为 True)。可以通过 trainable=False 声明不可训练参数,并用 assign / assign_add 原地更新、用 value() 读取:

w = tf.Variable([1, 2, 3], trainable=False)
print(w.trainable)                       # False
print(w.assign([3, 1, 4], read_value=True))   # 整体赋值
w.assign_add([2, -1, 2], read_value=False)    # 增量更新
print(w.value())                         # 读取当前值

初始化器(initializer)用来给出初始权重。仓库使用 GlorotNormal(Xavier 正态初始化):

tf.random.set_seed(1)
init = tf.keras.initializers.GlorotNormal()
tf.print(init(shape=(3,)))

v = tf.Variable(init(shape=(2, 3)))
tf.print(v)

用 tf.Module 组织参数:把参数放进自定义模块后,可通过 module.variables 与 module.trainable_variables 统一收集:

class MyModule(tf.Module):
    def __init__(self):
        init = tf.keras.initializers.GlorotNormal()
        self.w1 = tf.Variable(init(shape=(2, 3)), trainable=True)
        self.w2 = tf.Variable(init(shape=(1, 2)), trainable=False)

m = MyModule()
print('All module variables: ', [v.shape for v in m.variables])
print('Trainable variable:   ', [v.shape for v in m.trainable_variables])

一个重要的使用约束(仓库以注释形式标注):不能在 @tf.function 装饰的函数内部创建 Variable,否则会报 ValueError: tf.function-decorated function tried to create variables on non-first call.。正确做法是让变量在函数外创建、函数内引用,例如:

tf.random.set_seed(1)
w = tf.Variable(tf.random.uniform((3, 3)))

@tf.function
def compute_z(x):
    return tf.matmul(w, x)

x = tf.constant([[1], [2], [3]], dtype=tf.float32)
tf.print(compute_z(x))

GradientTape 自动微分:三种典型场景

场景一:计算损失关于可训练变量的梯度

w = tf.Variable(1.0)
b = tf.Variable(0.5)
print(w.trainable, b.trainable)

x = tf.convert_to_tensor([1.4])
y = tf.convert_to_tensor([2.1])

with tf.GradientTape() as tape:
    z = tf.add(tf.multiply(w, x), b)
    loss = tf.reduce_sum(tf.square(y - z))

dloss_dw = tape.gradient(loss, w)
tf.print('dL/dw : ', dloss_dw)

# 手工验证:2*x * ((w*x + b) - y)
tf.print(2*x * ((w*x + b) - y))

在 with tf.GradientTape() 上下文中执行前向计算,tape.gradient(loss, w) 即可拿到 ∂L/∂w。仓库还给出解析式 2*x*(w*x+b-y) 与 tape.gradient 的结果互相印证。

场景二:对不可训练张量求梯度(tape.watch())

with tf.GradientTape() as tape:
    tape.watch(x)                 # 显式“监视”非 Variable 张量
    z = tf.add(tf.multiply(w, x), b)
    loss = tf.square(y - z)

dloss_dx = tape.gradient(loss, x)
tf.print('dL/dx:', dloss_dx)

# 验证:2*w * ((w*x + b) - y)
tf.print(2*w * ((w*x + b) - y))

GradientTape 默认只追踪 Variable;若要对普通张量求导,需先 tape.watch(x)。这在监控输入扰动、做可解释性分析时很有用。

场景三:persistent=True 保留资源以多次求梯度

with tf.GradientTape(persistent=True) as tape:
    z = tf.add(tf.multiply(w, x), b)
    loss = tf.reduce_sum(tf.square(y - z))

dloss_dw = tape.gradient(loss, w)
dloss_db = tape.gradient(loss, b)

tf.print('dL/dw:', dloss_dw)
tf.print('dL/db:', dloss_db)

默认 GradientTape 只允许调用一次 gradient();设置 persistent=True 后可对多个目标反复求导(本例同时求 w 与 b 的梯度),使用后记得释放资源。

用优化器更新变量:optimizer.apply_gradients()

optimizer = tf.keras.optimizers.SGD()

optimizer.apply_gradients(zip([dloss_dw, dloss_db], [w, b]))

tf.print('Updated w:', w)
tf.print('Updated bias:', b)

zip([梯度列表], [变量列表]) 把梯度与参数一一配对,交给 apply_gradients 完成一步 SGD 更新——这就是"手动训练循环"的最小闭环,也是理解 Keras model.fit 底层原理的关键。

用 Keras API 简化常见架构实现

一个"学不会"的例子:单层 sigmoid 无法解决 XOR

XOR 是经典的非线性可分问题。仓库先生成 200 个二维样本,标签由 y = x1 * x2 < 0 决定:

tf.random.set_seed(1)
np.random.seed(1)

x = np.random.uniform(low=-1, high=1, size=(200, 2))
y = np.ones(len(x))
y[x[:, 0] * x[:, 1]<0] = 0

x_train = x[:100, :]
y_train = y[:100]
x_valid = x[100:, :]
y_valid = y[100:]

随后构造只有一层 sigmoid 输出的模型:

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(units=1,
                                input_shape=(2,),
                                activation='sigmoid'))

model.compile(optimizer=tf.keras.optimizers.SGD(),
              loss=tf.keras.losses.BinaryCrossentropy(),
              metrics=[tf.keras.metrics.BinaryAccuracy()])

hist = model.fit(x_train, y_train,
                 validation_data=(x_valid, y_valid),
                 epochs=200, batch_size=2, verbose=0)

训练 200 个 epoch 后,损失与验证准确率都停留在很差的水准——单层线性模型在特征空间里画不出 XOR 需要的非线性决策边界,这为下一节多层网络做了铺垫。Notebook 中还用 mlxtend.plotting.plot_decision_regions 绘制了决策区域图,直观展示分类失败。

用多层感知机(MLP)正确解决 XOR

换成带三个隐藏 ReLU 层、一个 sigmoid 输出的 MLP:

tf.random.set_seed(1)

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(units=4, input_shape=(2,), activation='relu'))
model.add(tf.keras.layers.Dense(units=4, activation='relu'))
model.add(tf.keras.layers.Dense(units=4, activation='relu'))
model.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))

model.compile(optimizer=tf.keras.optimizers.SGD(),
              loss=tf.keras.losses.BinaryCrossentropy(),
              metrics=[tf.keras.metrics.BinaryAccuracy()])

hist = model.fit(x_train, y_train,
                 validation_data=(x_valid, y_valid),
                 epochs=200, batch_size=2, verbose=0)

同样训练 200 个 epoch,训练/验证损失持续下降、binary_accuracy 与 val_binary_accuracy 稳定上升,决策区域图也呈现正确的"对角分裂"形态。对比两种模型可直观体会到非线性激活与隐藏层深度对表征能力的决定性影响。

配置层与编译模型:initializers / regularizers / activations

Keras 层支持细粒度配置。仓库示例给隐藏层指定了激活函数、权重初始化器与偏置初始化器,并给第二个隐藏层加了 L1 正则:

model = tf.keras.Sequential()

model.add(
    tf.keras.layers.Dense(
        units=16,
        activation=tf.keras.activations.relu,
        kernel_initializer=tf.keras.initializers.GlorotNormal(),
        bias_initializer=tf.keras.initializers.Constant(2.0)
    ))

model.add(
    tf.keras.layers.Dense(
        units=32,
        activation=tf.keras.activations.sigmoid,
        kernel_regularizer=tf.keras.regularizers.l1
    ))

model.build(input_shape=(None, 4))
model.summary()

要点:

  • initializers:tf.keras.initializers 提供 GlorotNormal、Constant 等,决定权重/偏置的初始分布;
  • regularizers:tf.keras.regularizers.l1 等给 kernel 加正则项,抑制过拟合;
  • activations:tf.keras.activations.relu / sigmoid 等以函数形式传入,与字符串 'relu' 等价;
  • model.build(input_shape=(None, 4)):触发"晚创建变量"(late variable creation)机制——在 build 之前网络不知道输入维度,build 之后各层权重才真正分配,随后可用 model.variables 查看每个参数的名字、可训练性与形状。

编译阶段则统一指定优化器、损失与评估指标:

model.compile(
    optimizer=tf.keras.optimizers.SGD(learning_rate=0.001),
    loss=tf.keras.losses.BinaryCrossentropy(),
    metrics=[tf.keras.metrics.Accuracy(),
             tf.keras.metrics.Precision(),
             tf.keras.metrics.Recall(),])

tf.keras.optimizers、tf.keras.losses、tf.keras.metrics 分别对应优化器、损失函数与度量指标;分类任务可叠加 BinaryAccuracy、Precision、Recall 等多项指标,训练历史会逐项记录。

函数式 API:显式连接更灵活

Sequential 只能处理单输入单输出的线性堆叠。函数式 API 通过"层即函数"的方式自由连接张量:

tf.random.set_seed(1)

## input layer:
inputs = tf.keras.Input(shape=(2,))

## hidden layers
h1 = tf.keras.layers.Dense(units=4, activation='relu')(inputs)
h2 = tf.keras.layers.Dense(units=4, activation='relu')(h1)
h3 = tf.keras.layers.Dense(units=4, activation='relu')(h2)

## output:
outputs = tf.keras.layers.Dense(units=1, activation='sigmoid')(h3)

## construct a model:
model = tf.keras.Model(inputs=inputs, outputs=outputs)

model.compile(optimizer=tf.keras.optimizers.SGD(),
              loss=tf.keras.losses.BinaryCrossentropy(),
              metrics=[tf.keras.metrics.BinaryAccuracy()])

hist = model.fit(x_train, y_train,
                 validation_data=(x_valid, y_valid),
                 epochs=200, batch_size=2, verbose=0)

tf.keras.Input(shape=(2,)) 定义输入占位,然后逐层"调用"(Dense(...)(h)),最后用 tf.keras.Model(inputs=inputs, outputs=outputs) 组装。这种写法支持分支、合并、多输入多输出,是构建复杂拓扑(如残差网络、多任务模型)的基础。

基于 Model 类的子类化:定义 __init__ 与 call

函数式 API 面向"计算图拓扑";子类化则面向"面向对象"的编程习惯,把网络写成一个类,只要求定义 __init__()(创建层)与 call()(前向逻辑):

class MyModel(tf.keras.Model):
    def __init__(self):
        super(MyModel, self).__init__()
        self.hidden_1 = tf.keras.layers.Dense(units=4, activation='relu')
        self.hidden_2 = tf.keras.layers.Dense(units=4, activation='relu')
        self.hidden_3 = tf.keras.layers.Dense(units=4, activation='relu')
        self.output_layer = tf.keras.layers.Dense(units=1, activation='sigmoid')

    def call(self, inputs):
        h = self.hidden_1(inputs)
        h = self.hidden_2(h)
        h = self.hidden_3(h)
        return self.output_layer(h)

tf.random.set_seed(1)

model = MyModel()
model.build(input_shape=(None, 2))
model.summary()

model.compile(optimizer=tf.keras.optimizers.SGD(),
              loss=tf.keras.losses.BinaryCrossentropy(),
              metrics=[tf.keras.metrics.BinaryAccuracy()])

hist = model.fit(x_train, y_train,
                 validation_data=(x_valid, y_valid),
                 epochs=200, batch_size=2, verbose=0)

call() 里的张量流就是前向传播本身,可在其中自由编写控制流(if、for、training 分支等),灵活性最高;代价是需要自行保证层变量在 __init__ 中创建(或配合 build)。

编写自定义 Keras 层:NoisyLinear 全解析

自定义层只需实现 __init__、build(晚创建变量)、call 与 get_config(序列化)。仓库中的 NoisyLinear 是一个"带噪声注入"的全连接层,训练时给输入加高斯噪声,推理时不加:

class NoisyLinear(tf.keras.layers.Layer):
    def __init__(self, output_dim, noise_stddev=0.1, **kwargs):
        self.output_dim = output_dim
        self.noise_stddev = noise_stddev
        super(NoisyLinear, self).__init__(**kwargs)

    def build(self, input_shape):
        self.w = self.add_weight(name='weights',
                                 shape=(input_shape[1], self.output_dim),
                                 initializer='random_normal',
                                 trainable=True)

        self.b = self.add_weight(shape=(self.output_dim,),
                                 initializer='zeros',
                                 trainable=True)

    def call(self, inputs, training=False):
        if training:
            batch = tf.shape(inputs)[0]
            dim = tf.shape(inputs)[1]
            noise = tf.random.normal(shape=(batch, dim),
                                     mean=0.0,
                                     stddev=self.noise_stddev)

            noisy_inputs = tf.add(inputs, noise)
        else:
            noisy_inputs = inputs
        z = tf.matmul(noisy_inputs, self.w) + self.b
        return tf.keras.activations.relu(z)

    def get_config(self):
        config = super(NoisyLinear, self).get_config()
        config.update({'output_dim': self.output_dim,
                       'noise_stddev': self.noise_stddev})
        return config

四个方法的作用:

  • __init__:保存超参数(output_dim、noise_stddev),并记得调用 super().__init__(**kwargs);
  • build:用 add_weight 按输入形状创建权重 w 与偏置 b,trainable=True 表示参与训练;
  • call:前向计算。training=False 参数由 Keras 在训练/推理时自动传入,借此区分是否注入噪声;
  • get_config:把构造参数写进配置,配合 Layer.from_config(config) 即可反序列化重建层(仓库随后用 NoisyLinear.from_config(noisy_layer.get_config()) 验证了这一点)。

自定义层可直接放进 Sequential 使用:

tf.random.set_seed(1)

model = tf.keras.Sequential([
    NoisyLinear(4, noise_stddev=0.1),
    tf.keras.layers.Dense(units=4, activation='relu'),
    tf.keras.layers.Dense(units=4, activation='relu'),
    tf.keras.layers.Dense(units=1, activation='sigmoid')])

model.build(input_shape=(None, 2))
model.compile(optimizer=tf.keras.optimizers.SGD(),
              loss=tf.keras.losses.BinaryCrossentropy(),
              metrics=[tf.keras.metrics.BinaryAccuracy()])

hist = model.fit(x_train, y_train,
                 validation_data=(x_valid, y_valid),
                 epochs=200, batch_size=2,
                 verbose=0)

在 XOR 任务上,这个带噪声注入的模型同样能收敛到不错的验证准确率,说明自定义层与标准 Keras 层在训练流程中完全兼容。

TensorFlow Estimators:更高层的机器学习接口

使用预置 Estimator 的四个步骤

从 ch14/ch14_part2.py 开头可以看到,Estimator 工作流固定为四步:

  1. Step 1:定义输入函数(input function),负责导入并组织数据;
  2. Step 2:定义特征列(feature columns),在 Estimator 与数据之间"架桥";
  3. Step 3:实例化一个 Estimator,或把 Keras 模型转换为 Estimator;
  4. Step 4:使用 Estimator 的 train()、evaluate()、predict() 完成训练、评估与预测。

特征列(feature columns)

特征列把原始数据(数值、分桶、类别)映射为模型可消费的特征。仓库以 auto-mpg(汽车油耗)回归数据集为例:先用 tf.keras.utils.get_file 下载数据,用 pandas 读入并做缺失值清洗、训练/测试划分与标准化(df_train.describe().transpose() 求出各数值列的均值/标准差,再做 z-score 归一化)。随后构造三类特征列:

numeric_features = []
for col_name in numeric_column_names:
    numeric_features.append(tf.feature_column.numeric_column(key=col_name))

数值列:numeric_column(key=...) 直接使用原始数值。

feature_year = tf.feature_column.numeric_column(key="ModelYear")

bucketized_features = []
bucketized_features.append(tf.feature_column.bucketized_column(
    source_column=feature_year,
    boundaries=[73, 76, 79]))

分桶列:bucketized_column 把连续特征按 boundaries=[73, 76, 79] 切分成离散区间,让线性模型也能捕捉阈值效应。

feature_origin = tf.feature_column.categorical_column_with_vocabulary_list(
    key='Origin',
    vocabulary_list=[1, 2, 3])

categorical_indicator_features = []
categorical_indicator_features.append(tf.feature_column.indicator_column(feature_origin))

类别列 + 指示列:categorical_column_with_vocabulary_list 声明类别词汇表(汽车产地 1/2/3),indicator_column 再把它展开为 one-hot 形式的指示特征。最后把所有特征列拼接:

all_feature_columns = (numeric_features +
                       bucketized_features +
                       categorical_indicator_features)

数据准备与输入函数

Estimator 的输入函数返回 tf.data.Dataset。训练输入函数要保证打乱(shuffle)、无限重复(repeat)、分批(batch):

def train_input_fn(df_train, batch_size=8):
    df = df_train.copy()
    train_x, train_y = df, df.pop('MPG')
    dataset = tf.data.Dataset.from_tensor_slices((dict(train_x), train_y))

    # shuffle, repeat, and batch the examples
    return dataset.shuffle(1000).repeat().batch(batch_size)

其中 dict(train_x) 让每条样本变成一个特征名字典(与特征列的 key 对应),标签列 MPG 被 pop 出来作为回归目标。评估输入函数不需要 repeat():

def eval_input_fn(df_test, batch_size=8):
    df = df_test.copy()
    test_x, test_y = df, df.pop('MPG')
    dataset = tf.data.Dataset.from_tensor_slices((dict(test_x), test_y))
    return dataset.batch(batch_size)

预置 Estimator:DNNRegressor 与 BoostedTreesRegressor

深度回归器 DNNRegressor

regressor = tf.estimator.DNNRegressor(
    feature_columns=all_feature_columns,
    hidden_units=[32, 10],
    model_dir='models/autompg-dnnregressor/')

hidden_units=[32, 10] 定义两个隐藏层(32 与 10 个神经元),model_dir 指定检查点(checkpoint)存放目录。仓库先计算总步数:

EPOCHS = 1000
BATCH_SIZE = 8
total_steps = EPOCHS * int(np.ceil(len(df_train) / BATCH_SIZE))
print('Training Steps:', total_steps)

然后训练、用 warm_start_from 热启动恢复训练、评估与预测:

regressor.train(
    input_fn=lambda:train_input_fn(df_train_norm, batch_size=BATCH_SIZE),
    steps=total_steps)

reloaded_regressor = tf.estimator.DNNRegressor(
    feature_columns=all_feature_columns,
    hidden_units=[32, 10],
    warm_start_from='models/autompg-dnnregressor/',
    model_dir='models/autompg-dnnregressor/')

eval_results = reloaded_regressor.evaluate(
    input_fn=lambda:eval_input_fn(df_test_norm, batch_size=8))
print('Average-Loss {:.4f}'.format(eval_results['average_loss']))

pred_res = regressor.predict(input_fn=lambda: eval_input_fn(df_test_norm, batch_size=8))
print(next(iter(pred_res)))

注意 input_fn 通过 lambda 包装,因为 Estimator 要求传入零参数函数;evaluate 会返回 average_loss 等指标;predict 以生成器方式逐条产出预测。

梯度提升树回归器 BoostedTreesRegressor

boosted_tree = tf.estimator.BoostedTreesRegressor(
    feature_columns=all_feature_columns,
    n_batches_per_layer=20,
    n_trees=200)

boosted_tree.train(
    input_fn=lambda:train_input_fn(df_train_norm, batch_size=BATCH_SIZE))

eval_results = boosted_tree.evaluate(
    input_fn=lambda:eval_input_fn(df_test_norm, batch_size=8))
print('Average-Loss {:.4f}'.format(eval_results['average_loss']))

n_trees=200 指定树的数量、n_batches_per_layer 控制每层训练的批次数。树模型无需数据标准化即可处理分桶/类别特征,与 DNN 回归器形成互补——这也是预置 Estimator 家族覆盖不同类型算法的体现。

用 Estimator 做 MNIST 手写数字分类

ch14/ch14_part3.py 先用 tensorflow_datasets(tfds)加载 MNIST:

BUFFER_SIZE = 10000
BATCH_SIZE = 64
NUM_EPOCHS = 20
steps_per_epoch = np.ceil(60000 / BATCH_SIZE)

def preprocess(item):
    image = item['image']
    label = item['label']
    image = tf.image.convert_image_dtype(image, tf.float32)
    image = tf.reshape(image, (-1,))
    return {'image-pixels':image}, label[..., tf.newaxis]

## Step 1: input functions
def train_input_fn():
    datasets = tfds.load(name='mnist')
    mnist_train = datasets['train']
    dataset = mnist_train.map(preprocess)
    dataset = dataset.shuffle(BUFFER_SIZE)
    dataset = dataset.batch(BATCH_SIZE)
    return dataset.repeat()

def eval_input_fn():
    datasets = tfds.load(name='mnist')
    mnist_test = datasets['test']
    dataset = mnist_test.map(preprocess).batch(BATCH_SIZE)
    return dataset

preprocess 把 28×28 图像转换为 float32 并展平为 784 维向量,特征字典键为 'image-pixels',标签补一个维度(label[..., tf.newaxis])。随后按四步流程搭建分类器:

## Step 2: feature column
image_feature_column = tf.feature_column.numeric_column(
    key='image-pixels', shape=(28*28))

## Step 3: instantiate the estimator
dnn_classifier = tf.estimator.DNNClassifier(
    feature_columns=[image_feature_column],
    hidden_units=[32, 16],
    n_classes=10,
    model_dir='models/mnist-dnn/')

## Step 4: train
dnn_classifier.train(
    input_fn=train_input_fn,
    steps=NUM_EPOCHS * steps_per_epoch)

eval_result = dnn_classifier.evaluate(input_fn=eval_input_fn)
print(eval_result)

DNNClassifier 与回归器同构,额外指定 n_classes=10(10 个数字类别);特征列把 'image-pixels' 声明为 shape=(28*28) 的数值列。训练 20 个 epoch 后 evaluate 会返回 accuracy、loss 等指标字典。

从 Keras 模型创建自定义 Estimator

最后,仓库演示了把第 14 章前面构建的 Keras 模型直接"包装"成 Estimator,复用到 XOR 数据上。先定义输入函数与特征列:

def train_input_fn(x_train, y_train, batch_size=8):
    dataset = tf.data.Dataset.from_tensor_slices(
        ({'input-features':x_train}, y_train.reshape(-1, 1)))
    return dataset.shuffle(100).repeat().batch(batch_size)

def eval_input_fn(x_test, y_test=None, batch_size=8):
    if y_test is None:
        dataset = tf.data.Dataset.from_tensor_slices(
            {'input-features':x_test})
    else:
        dataset = tf.data.Dataset.from_tensor_slices(
            ({'input-features':x_test}, y_test.reshape(-1, 1)))
    return dataset.batch(batch_size)

features = [
    tf.feature_column.numeric_column(
        key='input-features:', shape=(2,))
]

实操提示:输入函数字典中的特征 key 与特征列的 key、以及 Keras Input 层的 name 三者必须严格一致。仓库 ch14/ch14_part3.py 中特征列处写为 'input-features:'(带冒号),而输入函数与 Input 层使用 'input-features'——读者在实际运行时,应以特征列与输入函数/Input 层三者 key 统一为准。

接着构建 Keras 模型并转换:

model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(2,), name='input-features'),
    tf.keras.layers.Dense(units=4, activation='relu'),
    tf.keras.layers.Dense(units=4, activation='relu'),
    tf.keras.layers.Dense(units=4, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer=tf.keras.optimizers.SGD(),
              loss=tf.keras.losses.BinaryCrossentropy(),
              metrics=[tf.keras.metrics.BinaryAccuracy()])

my_estimator = tf.keras.estimator.model_to_estimator(
    keras_model=model,
    model_dir='models/estimator-for-XOR/')

tf.keras.estimator.model_to_estimator(keras_model=model, model_dir=...) 即 Step 3 的"从 Keras 模型创建 Estimator"。之后与预置 Estimator 完全一致地训练与评估:

num_epochs = 200
batch_size = 2
steps_per_epoch = np.ceil(len(x_train) / batch_size)

my_estimator.train(
    input_fn=lambda: train_input_fn(x_train, y_train, batch_size),
    steps=num_epochs * steps_per_epoch)

my_estimator.evaluate(
    input_fn=lambda: eval_input_fn(x_valid, y_valid, batch_size))

这展示了 Keras 与 Estimator 两种编程范式可以无缝衔接:先用 Keras 快速原型,再转换为 Estimator 以享受其分布式训练、检查点管理、热启动等工程化能力。

如何运行这些代码示例

ch14/README.md 给出了明确的运行建议:优先使用 Jupyter Notebook(.ipynb 文件),这样可以逐步执行代码,并把所有输出(含图表)集中在一个文档里,配合书阅读体验最佳。

使用 Jupyter Notebook

如果使用 Anaconda Python 发行版,一条命令即可安装 Jupyter Notebook:

conda install jupyter notebook

随后在终端启动:

jupyter notebook

浏览器会打开 Notebook 界面,在其中导航到包含目标 .ipynb 的目录(即仓库的 ch14 目录),点击 ch14_part1.ipynb、ch14_part2.ipynb 或 ch14_part3.ipynb 即可逐格运行。即便不安装 Jupyter,也可以直接点击仓库内的 .ipynb 文件进行在线预览。

在 Jupyter Notebook 中分步执行第 2 章示例代码的界面截图

带目录与章节标题的 Jupyter Notebook 示例界面截图

每份 Notebook 都内置了与书本一致的目录和章节标题,并嵌入书中原始图表,方便对照阅读。

使用 .py 脚本

如果你更习惯普通编辑器,仓库也把每份 Notebook 转换成了等价的 Python 脚本(ch14/ch14_part1.py、ch14/ch14_part2.py、ch14/ch14_part3.py),可以用任意纯文本编辑器查看和修改,或用 python ch14/ch14_part1.py 直接运行。

更完整的安装与环境配置说明,请参见 第 1 章 README。

小结

本章(ch14)从"计算机制"到底层开始,把 TensorFlow 的关键零件逐一拆解:v1 的计算图与 Session 如何被 v2 的 eager 执行与 @tf.function 取代;tf.Variable 如何承载并更新参数;GradientTape 如何用自动微分替代手推导数;Keras 的 Sequential、函数式 API、Model 子类化与自定义层四种建模方式各自适用于什么场景;以及 Estimator 如何用"输入函数 + 特征列 + 预置/自定义估计器"四步工作流,把 Keras 模型与工程化训练管线统一起来。配合仓库中的 ch14/ch14_part1.py、ch14/ch14_part2.py、ch14/ch14_part3.py 逐步运行,即可把这套知识转化为可直接复用的训练代码。

登录后查看全文
python-machine-learning-book-3rd-edition