TensorFlow Keras 是 TensorFlow 的高级 API,提供了易于使用且可扩展的神经网络库。以下是一些 Keras API 的基本指南。

模型构建

Keras 提供了多种模型构建方式,包括:

  • Sequential 模型:一种线性堆叠的模型,适合快速原型设计。
  • Functional API:允许您创建更复杂的模型,包括多输入、多输出和共享层。
  • Model subclassing:通过继承 tf.keras.Model 类来创建自定义模型。

更多关于模型构建的详细内容,请参阅模型构建指南

Keras 提供了丰富的层,包括:

  • 激活层:如 ReLU、Sigmoid、Tanh 等。
  • 卷积层:如 Conv1D、Conv2D、Conv3D 等。
  • 循环层:如 LSTM、GRU、SimpleRNN 等。

更多关于层的详细内容,请参阅层指南

损失和优化器

在训练模型时,选择合适的损失函数和优化器非常重要:

  • 损失函数:如 MSE、CategoricalCrossentropy 等。
  • 优化器:如 SGD、Adam、RMSprop 等。

更多关于损失和优化器的详细内容,请参阅损失和优化器指南

数据预处理

数据预处理是模型训练的重要步骤:

  • 数据加载:使用 tf.keras.preprocessing 模块加载和预处理数据。
  • 数据增强:使用 tf.keras.preprocessing.image.ImageDataGenerator 进行数据增强。

更多关于数据预处理的详细内容,请参阅数据预处理指南

示例

以下是一个简单的 Sequential 模型示例:

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)

更多示例代码,请参阅Keras 示例

TensorFlow Logo