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

第8章 TensorFlow 中的模块、层与模型

TensorFlow

Learn TensorFlow Core Guide

模块、层和模型简介

通过集合进行整理。保存并按偏好对内容进行分类。

在 TensorFlow 中进行机器学习,你通常需要定义、保存和恢复模型。

从抽象意义上说,模型是:

  • 一个在张量上计算某些内容的函数(前向传播)
  • 一些可以根据训练进行更新的变量

在本指南中,你将深入 Keras 表面之下,查看 TensorFlow 模型是如何定义的。这涵盖了 TensorFlow 如何收集和恢复变量及模型。

Setup

import tensorflow as tf
import keras
from datetime import datetime

%load_ext tensorboard

2023-10-18 01:21:05.536666: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered 2023-10-18 01:21:05.536712: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered 2023-10-18 01:21:05.536766: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered

TensorFlow 模块

大多数模型由层组成。层是具有已知数学结构的可复用函数,且包含可训练变量。在 TensorFlow 中,大多数高层的层和模型实现(如 Keras 或 Sonnet)都基于同一个基础类:tf.Module。

构建模块

下面是一个对标量张量进行操作的最简 tf.Module 示例:

class SimpleModule(tf.Module):
  def __init__(self, name=None):
    super().__init__(name=name)
    self.a_variable = tf.Variable(5.0, name="train_me")
    self.non_trainable_variable = tf.Variable(5.0, trainable=False, name="do_not_train_me")
  def __call__(self, x):
    return self.a_variable * x + self.non_trainable_variable

simple_module = SimpleModule(name="simple")

simple_module(tf.constant(5.0))

2023-10-18 01:21:08.181350: W tensorflow/core/common_runtime/gpu/gpu_device.cc:2211] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform. Skipping registering GPU devices... <tf.Tensor: shape=(), dtype=float32, numpy=30.0>

模块(以及由此延伸的层)是深度学习术语中的“对象”:它们具有内部状态以及使用这些状态的方法。

__call__ 本身没有特殊之处,它只是让模块表现得像一个 Python 可调用对象;你可以用任何想要的函数来调用你的模型。

你可以出于任何原因开启或关闭变量的可训练性,包括在微调期间冻结层和变量。

通过子类化 tf.Module,分配给对象属性的任何 tf.Variable 或 tf.Module 实例都会自动被收集。这使得你可以保存和加载变量,并创建 tf.Module 集合。

# 所有可训练变量
print("trainable variables:", simple_module.trainable_variables)
# 所有变量
print("all variables:", simple_module.variables)

trainable variables: (<tf.Variable 'train_me:0' shape=() dtype=float32, numpy=5.0>,) all variables: (<tf.Variable 'train_me:0' shape=() dtype=float32, numpy=5.0>, <tf.Variable 'do_not_train_me:0' shape=() dtype=float32, numpy=5.0>)

这是一个由模块组成的两层线性层模型示例。

首先是一个 dense(线性)层:

class Dense(tf.Module):
  def __init__(self, in_features, out_features, name=None):
    super().__init__(name=name)
    self.w = tf.Variable(
      tf.random.normal([in_features, out_features]), name='w')
    self.b = tf.Variable(tf.zeros([out_features]), name='b')
  def __call__(self, x):
    y = tf.matmul(x, self.w) + self.b
    return tf.nn.relu(y)

然后是完整模型,它创建两个层实例并对它们应用:

class SequentialModule(tf.Module):
  def __init__(self, name=None):
    super().__init__(name=name)

    self.dense_1 = Dense(in_features=3, out_features=3)
    self.dense_2 = Dense(in_features=3, out_features=2)

  def __call__(self, x):
    x = self.dense_1(x)
    return self.dense_2(x)

# 你构建了一个模型!
my_model = SequentialModule(name="the_model")

# 调用它,使用随机结果
print("Model results:", my_model(tf.constant([[2.0, 2.0, 2.0]])))

Model results: tf.Tensor([[0. 3.415034]], shape=(1, 2), dtype=float32)

tf.Module 实例会自动递归收集分配给它的任何 tf.Variable 或 tf.Module 实例。这允许你使用单个模型实例管理 tf.Module 集合,并保存和加载整个模型。

print("Submodules:", my_model.submodules)

Submodules: (<__main__.Dense object at 0x7f7931aea250>, <__main__.Dense object at 0x7f77ed5b8a00>)

for var in my_model.variables:
  print(var, "\n")

<tf.Variable 'b:0' shape=(3,) dtype=float32, numpy=array([0., 0., 0.], dtype=float32)> <tf.Variable 'w:0' shape=(3, 3) dtype=float32, numpy= array([[-2.8161757, -2.6065955, 1.9061812], [-0.9430401, -0.4624743, -0.4531979], [-1.3428234, 0.7062293, 0.7874674]], dtype=float32)> <tf.Variable 'b:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)> <tf.Variable 'w:0' shape=(3, 2) dtype=float32, numpy= array([[ 1.0474309 , -0.6920227 ], [ 1.2405277 , 0.

评论 (0)