在TensorFlow中使用Keras构建深度学习模型是一种非常流行且高效的方式。Keras作为TensorFlow的高级API,提供了简单易用的接口,同时保留了强大的功能。下面将通过一个完整的实例来演示如何使用Keras构建、训练和评估一个深度学习模型。
首先确保安装了TensorFlow库。可以通过以下命令安装:
pip install tensorflow
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
我们将使用经典的MNIST手写数字数据集。这是一个包含70,000张28x28像素灰度图像的数据集,每张图像代表一个手写的数字(0-9)。
# 加载数据集
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# 归一化处理
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
# 转换为四维张量 (样本数, 高度, 宽度, 通道数)
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
# 将标签转换为one-hot编码
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
我们使用Sequential API来构建一个简单的卷积神经网络(CNN)。
model = keras.Sequential([
layers.InputLayer(input_shape=(28, 28, 1)),
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(10, activation="softmax")
])
model.summary()
在编译模型时,我们需要指定优化器、损失函数以及评估指标。
model.compile(
loss="categorical_crossentropy",
optimizer="adam",
metrics=["accuracy"]
)
接下来,我们开始训练模型。这里设置训练轮次为10,批量大小为128。
history = model.fit(
x_train,
y_train,
batch_size=128,
epochs=10,
validation_split=0.1
)
训练完成后,我们可以对测试集进行评估。
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f"Test accuracy: {test_acc}")
训练好的模型可以保存下来,以便后续使用。
# 保存模型
model.save("mnist_model.h5")
# 加载模型
loaded_model = keras.models.load_model("mnist_model.h5")
我们可以绘制训练过程中准确率和损失的变化曲线。
graph TD; A[Start] --> B[Load Data]; B --> C[Preprocess Data]; C --> D[Build Model]; D --> E[Compile Model]; E --> F[Train Model]; F --> G[Evaluate Model]; G --> H[Save Model]; H --> I[End];
import matplotlib.pyplot as plt
# 绘制训练 & 验证的准确率
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()
# 绘制训练 & 验证的损失值
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()