使用tensorflow2.0进行卷积模型训练与效果展示

1.使用tensorflow加载数据,并进行数据的预处理

import tensorflow as tf
from sklearn.model_selection import train_test_split
import numpy as np

# 1. 加载数据(TF 2.x 方式)
(x_train_full, y_train_full), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

# 2. 进行数据预处理,CNN(TensorFlow) → 添加通道 (样本数, 28, 28, 1),数据默认(28,28)形状

x_train_full = x_train_full.reshape(-1,28, 28, 1) / 255.0  # 归一化到 [0,1]
x_test = x_test.reshape(-1,28, 28, 1) / 255.0

# 3. 使用 sklearn 分割训练集和验证集
# test_size=10000 表示分出10000条作为验证集
# random_state=42 保证每次分割结果一致
x_train, x_validation, y_train, y_validation = train_test_split(
    x_train_full,
    y_train_full,
    test_size=10000,  # 分出10000条
    random_state=42,   # 固定随机种子,确保可重复性
    stratify=y_train_full  # 保持类别分布均衡(可选)
)

# 4. 进行 one-hot 编码(用于某些损失函数)
y_train_one_hot = tf.keras.utils.to_categorical(y_train, 10)
y_validation_one_hot = tf.keras.utils.to_categorical(y_validation,10)
y_test_one_hot = tf.keras.utils.to_categorical(y_test, 10)

  

 2.构建卷积模型

一些常用参数如下:

  1. activation:选择的激活函数,常用relu
  2. filters:特征图的个数
  3. kernel_size:设置卷积窗口的大小
  4. strides:指定卷积的步长(stride)长度
  5. padding:填充,图片处理后的需要做的操作
# 5. 构建模型(使用 Keras 的 Input 层)
# 如果要使用CPU进行运行,图片大小需要设置成28*28/64*64的;如使用GPU忽略
model = tf.keras.Sequential([
    # 显式添加 Input 层
    tf.keras.layers.Input(shape=(28, 28, 1)),
    tf.keras.layers.Conv2D(100,(3,3),activation='relu'),
    tf.keras.layers.MaxPool2D(2,2),
    tf.keras.layers.Conv2D(64,(3,3),activation='relu'),
    tf.keras.layers.MaxPool2D(2,2),
    tf.keras.layers.Conv2D(128,(3,3),activation='relu'),
    tf.keras.layers.MaxPool2D(2,2),
    #全连接层
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

  3.编译模型

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
              loss='categorical_crossentropy',
              metrics=['accuracy'])

  4.训练模型及效果展示

#steps_per_epoch相当于是给定一个停止条件,因为生成器会不断的产生batch数据,它不知道一个epoch里面要执行多少steps
history = model.fit(
    x_train, y_train_one_hot,
    steps_per_epoch=500, # 数据集大小=batch-size * steps_per_epoch
    batch_size=100,
    epochs=10,
    validation_data=(x_validation, y_validation_one_hot),  # 直接用验证集
    verbose=1
)

#效果展示
import matplotlib.pyplot as plt
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(len(acc))

plt.plot(epochs,acc,'bo',label="Training accuracy")
plt.plot(epochs,val_acc,'b',label ="Validation accuracy")
plt.legend()
plt.title("Training and Validation accuracy")
plt.xlabel('epochs')
plt.ylabel('accuracy')

plt.figure()
plt.plot(epochs,loss,'bo',label="Training loss")
plt.plot(epochs,val_loss,'b',label ="Validation loss")
plt.legend()
plt.title("Training and Validation loss")
plt.xlabel('epochs')
plt.ylabel('loss')
plt.show()

  训练效果如下图展示:

屏幕截图2026.03.20

屏幕截图2026.03.20

 

 

posted @ 2026-03-20 16:18  sunshine_coast  阅读(5)  评论(0)    收藏  举报