实训
``import tensorflow as tf
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
1. 加载并预处理 CIFAR-10 数据集
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
归一化:将像素值缩放到 0-1 范围
x_train = x_train / 255.0
x_test = x_test / 255.0
独热编码:将标签转换为分类向量
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
2. 构建卷积神经网络模型
model = Sequential([
# 第一层卷积:32 个 3x3 过滤器,激活函数为 ReLU
Conv2D(32, (3, 3), activation='relu', padding='same', input_shape=(32, 32, 3)),
# 池化层:2x2 最大池化
MaxPooling2D((2, 2)),
# 第二层卷积:64 个 3x3 过滤器
Conv2D(64, (3, 3), activation='relu', padding='same'),
MaxPooling2D((2, 2)),
# 第三层卷积:128 个 3x3 过滤器
Conv2D(128, (3, 3), activation='relu', padding='same'),
MaxPooling2D((2, 2)),
# 展平层:将卷积输出转换为一维向量
Flatten(),
# 全连接层:512 个神经元,激活函数为 ReLU
Dense(512, activation='relu'),
# Dropout 层:防止过拟合
Dropout(0.5),
# 输出层:10 个神经元(对应 10 个类别),激活函数为 softmax
Dense(10, activation='softmax')
])
3. 编译模型
model.compile(
optimizer='adam', # 优化器选择 Adam
loss='categorical_crossentropy', # 损失函数选择分类交叉熵
metrics=['accuracy'] # 评估指标选择准确率
)
4. 训练模型
history = model.fit(
x_train, y_train,
epochs=30, # 训练轮次
batch_size=64, # 批次大小
validation_split=0.2 # 从训练集中划分 20% 作为验证集
)
5. 评估模型
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f'测试集准确率:{test_acc:.2%}')
6. 可视化训练过程(可选)
plt.figure(figsize=(12, 4))
绘制准确率曲线
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='训练准确率')
plt.plot(history.history['val_accuracy'], label='验证准确率')
plt.xlabel('轮次')
plt.ylabel('准确率')
plt.legend()
绘制损失曲线
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='训练损失')
plt.plot(history.history['val_loss'], label='验证损失')
plt.xlabel('轮次')
plt.ylabel('损失')
plt.legend()
plt.show()``

浙公网安备 33010602011771号