欢迎来到 TensorFlow Keras 的快速入门!以下是使用 Keras 构建和训练机器学习模型的基本步骤:

1. 安装 TensorFlow

确保已安装 TensorFlow:

pip install tensorflow

📌 了解更多安装指南

2. 加载数据

以 MNIST 手写数字数据集为例:

import tensorflow as tf
mnist = tf.keras.datasets.mnist.load_data()
(x_train, y_train), (x_test, y_test) = mnist

3. 构建模型

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax')
])
神经网络结构示意图

4. 编译模型

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

5. 训练模型

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

📊 查看训练过程可视化

6. 评估模型

test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f"测试准确率: {test_acc*100:.1f}%")

需要进一步学习 Keras 的高级功能吗?👉 探索 Keras 概述文档