Skip to content

Keras - Backend Configuration

理解 Keras 与其底层计算引擎(backend)之间的关系是很有帮助的,尽管现在直接进行后端配置不如过去常见了。

最初,Keras 被设计为一个 backend-agnostic(后端无关)的 API。这意味着你可以编写 Keras 代码,并选择在不同的深度学习框架上运行它,比如 TensorFlow、Theano 或 Microsoft Cognitive Toolkit (CNTK)。用户可以通过一个配置文件(~/.keras/keras.json)切换后端。

# 示例:旧的 keras.json 结构(仅供历史背景参考)
# {
# "image_data_format": "channels_last",
# "epsilon": 1e-07,
# "floatx": "float32",
# "backend": "tensorflow" # 可以改为 "theano" 或 "cntk"
# }

在深度学习框架格局快速演变的早期,这种灵活性是一个关键优势。

当前标准:tf.keras 与 TensorFlow 集成

Section titled “当前标准:tf.keras 与 TensorFlow 集成”

随着 TensorFlow 2.x 的发布,Keras 成为了 TensorFlow 的官方高层 API。现在使用的实现是 tf.keras,它与 TensorFlow 紧密集成,并只使用 TensorFlow 作为其唯一后端。

主要影响:

  • **无法切换后端:**你不再通过 keras.json 切换后端。当你使用 tf.keras 时,你本质上就是在使用 TensorFlow 后端。
  • 无缝生态系统:tf.keras 模型可以直接与整个 TensorFlow 生态系统集成,包括用于高效输入管道的 tf.data、用于生产级 ML 管道的 TensorFlow Extended (TFX)、用于移动/嵌入式部署的 TensorFlow Lite,以及用于可伸缩模型部署的 TensorFlow Serving。
  • **性能:**利用 TensorFlow 优化的操作、图执行(通过 tf.function)和硬件加速(GPU/TPU)变得简单直接。
  • **配置:**诸如浮点精度(floatx)或图像数据格式(image_data_format)之类的设置通常由 TensorFlow 的全局设置处理或推断得出,而不是单独的 Keras 配置文件。默认的 image_data_format 通常是 ‘channels_last’((batch, height, width, channels)),这在 TensorFlow 中很常见。

虽然你不直接配置后端本身,但你可以检查由 Keras 后端模块(与 TensorFlow 接口)管理的默认设置:

import tensorflow as tf
from tensorflow.keras import backend as K
# Check the default float type
print("Default float type:", K.floatx()) # 通常是 'float32'
# Check the default image data format
print("Image data format:", K.image_data_format()) # 通常是 'channels_last'
# Check the default epsilon value (for numerical stability)
print("Epsilon:", K.epsilon()) # 通常是 1e-07

全局更改这些默认值(例如,K.set_floatx('float64'))是可能的,但通常只在你有一个特定原因并理解其影响(例如,性能、内存使用)时才建议这样做。

tf.keras.backend 模块仍然存在,并提供低级张量操作(例如 K.dot, K.sum, K.relu)。这些函数在内部调用相应的 TensorFlow 操作。虽然你可以使用它们,但在 TensorFlow 2.x 中,为了在层或模型内部进行自定义计算,尤其是在使用模型子类化(model subclassing)或自定义层(custom layers)时,使用直接的 TensorFlow API(tf.*)通常更符合习惯。

总之,Keras 中后端配置的概念已经演变。使用 tf.keras,你是在 TensorFlow 生态系统中工作,无需管理单独的后端选择,并可深度集成 TensorFlow 的强大功能。