使用AlexNet神经网络

AlexNet神经网络

1.导包

from tensorflow.keras.preprocessing.image import ImageDataGenerator
import pathlib
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models

2.定义超参数

# 定义超参数

#用于指定存储图像数据的位置
data_dir = "D:/lx/"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*.jpg')))
print("图片总数为:", image_count)

#这是一个整数变量,表示在训练模型时每个批次的图像数量。批量大小是训练神经网络时一个重要的超参数,它影响了模型的收敛速度和稳定性。
batch_size = 32

#有的图像在训练之前将被统一调整为180x180像素的大小。
img_height = 180
img_width = 180

3.加载数据

# 使用image_dataset_from_directory()将数据加载到tf.data.Dataset中

#创建了一个训练数据集。函数的参数包括:
#data_dir:之前定义的图像数据目录路径。
#validation_split=0.2:指定从数据集中划分出20%作为验证集。
#subset="training":指示这个数据集是用于训练的。
#seed=123:设置随机种子,以确保数据集划分的可重复性。
#image_size=(img_height, img_width):指定图像的大小。
#batch_size=batch_size:指定每个批次的图像数量,这里使用之前定义的batch_size。

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,  # 验证集0.2
    subset="training",
    seed=123,
    image_size=(img_height, img_width),
    batch_size=batch_size)



#创建了一个验证数据集
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,
    subset="validation",
    seed=123,
    image_size=(img_height, img_width),
    batch_size=batch_size)

#从训练数据集中获取类别名称列表。这些类别名称是数据集中子目录的名称,每个子目录包含同一类别的图像。
class_names = train_ds.class_names

print(class_names)

4.可视化

plt.figure(figsize=(16, 8))
for images, labels in train_ds.take(1):
    for i in range(16):
        ax = plt.subplot(4, 4, i + 1)
        # plt.imshow(images[i], cmap=plt.cm.binary)
        plt.imshow(images[i].numpy().astype("uint8"))
        #为每个子图设置标题,标题是图像对应的类别名称。labels[i]是图像的标签(一个整数)
        plt.title(class_names[labels[i]])
        plt.axis("off")
plt.show()

5.构建图像增强生成器

# 再次检查数据
for image_batch, labels_batch in train_ds:
    print(image_batch.shape)
    print(labels_batch.shape)
    break

# 构建图像加强生成器
# -确保模型能很好地泛化,我建议您始终执行数据增强。
#它是一个图像数据增强工具。这个生成器可以随机变换图像,以增加训练数据的多样性,从而提高模型的泛化能力。
参数包括:
#Rotation_range=30:随机旋转图像的角度范围。
#width_shift_range=0.1:图像水平方向上随机平移的范围(相对于总宽度的比例)。
#height_shift_range=0.1:图像垂直方向上随机平移的范围(相对于总高度的比例)。
#shear_range=0.2:随机错切变换的范围。
#zoom_range=0.2:随机缩放图像的范围。
#horizontal_flip=True:随机水平翻转图像。
#fill_mode="nearest":填充新创建像素的方法。
#x = aug.flow(image_batch, labels_batch):使用aug生成器对第一个批次的图像和标签进行实时增强。flow()方法接受图像和标签,返回一个批量增强数据的Numpy数组。

aug = ImageDataGenerator(rotation_range=30, width_shift_range=0.1,
                         height_shift_range=0.1, shear_range=0.2, zoom_range=0.2,
                         horizontal_flip=True, fill_mode="nearest")
x = aug.flow(image_batch, labels_batch)

#这是一个TensorFlow推荐的用于优化数据管道的性能的参数。它可以自动调整内部缓冲区的大小,以最大化数据加载和处理的效率。
AUTOTUNE = tf.data.AUTOTUNE

6.缓存和优化数据集

# 将数据集缓存到内存中,加快速度
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)

7.构建模型

# 构建AlexNet模型
model = models.Sequential([
    layers.experimental.preprocessing.Rescaling(1. / 255, input_shape=(img_height, img_width, 3)),
    
    # 第一个卷积层
    layers.Conv2D(96, (11, 11), strides=(4, 4), activation='relu', padding='same'),
    layers.BatchNormalization(),
    layers.MaxPooling2D((3, 3), strides=(2, 2)),
    
    # 第二个卷积层
    layers.Conv2D(256, (5, 5), strides=(1, 1), activation='relu', padding='same'),
    layers.BatchNormalization(),
    layers.MaxPooling2D((3, 3), strides=(2, 2)),
    
    # 第三个卷积层
    layers.Conv2D(384, (3, 3), strides=(1, 1), activation='relu', padding='same'),
    
    # 第四个卷积层
    layers.Conv2D(384, (3, 3), strides=(1, 1), activation='relu', padding='same'),
    
    # 第五个卷积层
    layers.Conv2D(256, (3, 3), strides=(1, 1), activation='relu', padding='same'),
    layers.MaxPooling2D((3, 3), strides=(2, 2)),
    
    # 展平层
    layers.Flatten(),
    
    # 第一个全连接层
    layers.Dense(4096, activation='relu'),
    layers.Dropout(0.5),
    
    # 第二个全连接层
    layers.Dense(4096, activation='relu'),
    layers.Dropout(0.5),
    
    # 输出层
    layers.Dense(num_classes)
])

# 设置优化器
opt = tf.keras.optimizers.Adam(learning_rate=0.0001)

8.编译训练模型

# 设置优化器
# 设置优化器
opt = tf.keras.optimizers.Adam(learning_rate=0.0001)

# 编译模型
model.compile(optimizer=opt,
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

EPOCHS = 30
BS = 5
# model.fit 可同时处理训练和即时扩充的增强数据。
# 我们必须将训练数据作为第一个参数传递给生成器。生成器将根据我们先前进行的设置生成批量的增强训练数据。
for images_train, labels_train in train_ds:
    continue
for images_test, labels_test in val_ds:
    continue
    
# 训练模型
history = model.fit(train_ds,
                    validation_data=val_ds,
                    epochs=EPOCHS)

9.评估模型

# 画出训练精确度和损失图
N = np.arange(0, EPOCHS)
plt.style.use("ggplot")
plt.figure()
plt.plot(N, history.history["loss"], label="train_loss")
plt.plot(N, history.history["val_loss"], label="val_loss")
plt.plot(N, history.history["accuracy"], label="train_acc")
plt.plot(N, history.history["val_accuracy"], label="val_acc")
plt.title("Aug Training Loss and Accuracy")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend(loc='upper right')  # legend显示位置
plt.show()

test_loss, test_acc = model.evaluate(val_ds, verbose=2)
print(test_loss, test_acc)

10.可视化结果

# 画出训练精确度和损失图
N = np.arange(0, EPOCHS)
plt.style.use("ggplot")
plt.figure()
plt.plot(N, history.history["loss"], label="train_loss")
plt.plot(N, history.history["val_loss"], label="val_loss")
plt.plot(N, history.history["accuracy"], label="train_acc")
plt.plot(N, history.history["val_accuracy"], label="val_acc")
plt.title("Aug Training Loss and Accuracy")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend(loc='upper right')  # legend显示位置
plt.show()

test_loss, test_acc = model.evaluate(val_ds, verbose=2)
print(test_loss, test_acc)

  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值