目录
目标
准备工作
步骤1: 导入必要的库
步骤2: 加载和准备数据
步骤3: 构建模型
步骤4: 训练模型
步骤5: 评估模型
步骤6: 可视化训练过程
步骤7: 模型预测
步骤8: 模型保存与加载
总结
基于Python和TensorFlow/Keras框架的大模型实战教程。这个教程将涵盖从数据准备到模型训练、评估和部署的整个流程。我们将以一个简单的图像分类任务为例进行说明。
通过本教程,您将学会如何使用TensorFlow/Keras构建和训练一个深度学习模型来识别手写数字(MNIST数据集)。
确保您的环境中已安装了以下软件:
python
深色版本
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
import numpy as np
python
深色版本
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# 数据预处理
x_train, x_test = x_train / 255.0, x_test / 255.0 # 归一化
x_train = x_train[..., tf.newaxis] # 增加通道维度
x_test = x_test[..., tf.newaxis]
# 创建数据集
train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(10000).batch(32)
test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)
python
深色版本
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(10)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
python
深色版本
history = model.fit(train_ds, epochs=10, validation_data=test_ds)
python
深色版本
test_loss, test_acc = model.evaluate(test_ds, verbose=2)
print('\nTest accuracy:', test_acc)
python
深色版本
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0, 1])
plt.legend(loc='lower right')
plt.show()
python
深色版本
predictions = model.predict(x_test[:10])
for i in range(10):
print(f"Predicted: {np.argmax(predictions[i])}, Actual: {y_test[i]}")
python
深色版本
# 保存模型
model.save('mnist_model.h5')
# 加载模型
loaded_model = tf.keras.models.load_model('mnist_model.h5')
以上步骤展示了如何使用TensorFlow/Keras构建、训练和评估一个简单的卷积神经网络(CNN)模型来进行手写数字识别。通过这个例子,您可以了解深度学习模型的基本构建流程,包括数据准备、模型构建、训练、评估和保存。您可以根据自己的需求调整模型结构和参数,以适应不同的任务和数据集。