深度学习笔记18_TensorFlow实现猫狗识别

一、我的环境

1.语言环境:Python 3.9

2.编译器:Pycharm

3.深度学习环境:TensorFlow 2.10.0

二、GPU设置

若使用的是cpu则可忽略

import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")

if gpus:
    gpu0 = gpus[0] #如果有多个GPU,仅使用第0个GPU
    tf.config.experimental.set_memory_growth(gpu0, True) #设置GPU显存用量按需使用
    tf.config.set_visible_devices([gpu0],"GPU")

三**、导入数据**

python 复制代码
import matplotlib.pyplot as plt
# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

import os,PIL,pathlib

#隐藏警告
import warnings
warnings.filterwarnings('ignore')

data_dir = "./data"
data_dir = pathlib.Path(data_dir)

image_count = len(list(data_dir.glob('*/*')))

print("图片总数为:",image_count)
#图片总数为:3400

四**、数据预处理**

python 复制代码
batch_size = 8
img_height = 224
img_width = 224

"""
关于image_dataset_from_directory()的详细介绍可以参考文章:https://mtyjkh.blog.csdn.net/article/details/117018789
"""
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,
    subset="training",
    seed=12,
    image_size=(img_height, img_width),
    batch_size=batch_size)

"""
关于image_dataset_from_directory()的详细介绍可以参考文章:https://mtyjkh.blog.csdn.net/article/details/117018789
"""
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,
    subset="validation",
    seed=12,
    image_size=(img_height, img_width),
    batch_size=batch_size)
class_names = train_ds.class_names
print(class_names)

运行结果:

python 复制代码
['cat', 'dog']

五、可视化图片

python 复制代码
plt.figure(figsize=(15, 10))  # 图形的宽为15高为10

for images, labels in train_ds.take(1):
    for i in range(8):
        
        ax = plt.subplot(5, 8, i + 1) 
        plt.imshow(images[i])
        plt.title(class_names[labels[i]])
        
        plt.axis("off")
plt.show()

运行结果:

​​

再次检查数据:

for image_batch, labels_batch in train_ds:
    print(image_batch.shape)
    print(labels_batch.shape)
    break

运行结果:

(32, 224, 224, 3)
(32,)

六、配置数据集

  • shuffle() :打乱数据,关于此函数的详细介绍可以参考:https://zhuanlan.zhihu.com/p/42417456
  • prefetch():预取数据,加速运行
  • cache():将数据集缓存到内存当中,加速运行
python 复制代码
AUTOTUNE = tf.data.AUTOTUNE

def preprocess_image(image,label):
    return (image/255.0,label)

# 归一化处理
train_ds = train_ds.map(preprocess_image, num_parallel_calls=AUTOTUNE)
val_ds   = val_ds.map(preprocess_image, num_parallel_calls=AUTOTUNE)

train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds   = val_ds.cache().prefetch(buffer_size=AUTOTUNE)

七、自建模型

python 复制代码
from tensorflow.keras import layers, models, Input
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout

def VGG16(nb_classes, input_shape):
    input_tensor = Input(shape=input_shape)
    # 1st block
    x = Conv2D(64, (3,3), activation='relu', padding='same',name='block1_conv1')(input_tensor)
    x = Conv2D(64, (3,3), activation='relu', padding='same',name='block1_conv2')(x)
    x = MaxPooling2D((2,2), strides=(2,2), name = 'block1_pool')(x)
    # 2nd block
    x = Conv2D(128, (3,3), activation='relu', padding='same',name='block2_conv1')(x)
    x = Conv2D(128, (3,3), activation='relu', padding='same',name='block2_conv2')(x)
    x = MaxPooling2D((2,2), strides=(2,2), name = 'block2_pool')(x)
    # 3rd block
    x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv1')(x)
    x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv2')(x)
    x = Conv2D(256, (3,3), activation='relu', padding='same',name='block3_conv3')(x)
    x = MaxPooling2D((2,2), strides=(2,2), name = 'block3_pool')(x)
    # 4th block
    x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv1')(x)
    x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv2')(x)
    x = Conv2D(512, (3,3), activation='relu', padding='same',name='block4_conv3')(x)
    x = MaxPooling2D((2,2), strides=(2,2), name = 'block4_pool')(x)
    # 5th block
    x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv1')(x)
    x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv2')(x)
    x = Conv2D(512, (3,3), activation='relu', padding='same',name='block5_conv3')(x)
    x = MaxPooling2D((2,2), strides=(2,2), name = 'block5_pool')(x)
    # full connection
    x = Flatten()(x)
    x = Dense(4096, activation='relu',  name='fc1')(x)
    x = Dense(4096, activation='relu', name='fc2')(x)
    output_tensor = Dense(nb_classes, activation='softmax', name='predictions')(x)

    model = Model(input_tensor, output_tensor)
    return model

model=VGG16(1000, (img_width, img_height, 3))
model.summary()

运行结果:

python 复制代码
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 input_1 (InputLayer)        [(None, 224, 224, 3)]     0

 block1_conv1 (Conv2D)       (None, 224, 224, 64)      1792

 block1_conv2 (Conv2D)       (None, 224, 224, 64)      36928

 block1_pool (MaxPooling2D)  (None, 112, 112, 64)      0

 block2_conv1 (Conv2D)       (None, 112, 112, 128)     73856

 block2_conv2 (Conv2D)       (None, 112, 112, 128)     147584

 block2_pool (MaxPooling2D)  (None, 56, 56, 128)       0

 block3_conv1 (Conv2D)       (None, 56, 56, 256)       295168

 block3_conv2 (Conv2D)       (None, 56, 56, 256)       590080

 block3_conv3 (Conv2D)       (None, 56, 56, 256)       590080

 block3_pool (MaxPooling2D)  (None, 28, 28, 256)       0

 block4_conv1 (Conv2D)       (None, 28, 28, 512)       1180160

 block4_conv2 (Conv2D)       (None, 28, 28, 512)       2359808

 block4_conv3 (Conv2D)       (None, 28, 28, 512)       2359808

 block4_pool (MaxPooling2D)  (None, 14, 14, 512)       0

 block5_conv1 (Conv2D)       (None, 14, 14, 512)       2359808

 block5_conv2 (Conv2D)       (None, 14, 14, 512)       2359808

 block5_conv3 (Conv2D)       (None, 14, 14, 512)       2359808

 block5_pool (MaxPooling2D)  (None, 7, 7, 512)         0

 flatten (Flatten)           (None, 25088)             0

 fc1 (Dense)                 (None, 4096)              102764544

 fc2 (Dense)                 (None, 4096)              16781312

 predictions (Dense)         (None, 1000)              4097000

=================================================================
Total params: 138,357,544
Trainable params: 138,357,544
Non-trainable params: 0
_________________________________________________________________

八、编译

在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:

  • 损失函数(loss):用于衡量模型在训练期间的准确率。
  • 优化器(optimizer):决定模型如何根据其看到的数据和自身的损失函数进行更新。
  • 指标(metrics):用于监控训练和测试步骤。以下示例使用了准确率,即被正确分类的图像的比率。
python 复制代码
model.compile(optimizer="adam",
              loss     ='sparse_categorical_crossentropy',
              metrics  =['accuracy'])

九、训练模型

python 复制代码
epochs = 20

history = model.fit(
    train_ds,
    validation_data=val_ds,
    epochs=epochs
)

from tqdm import tqdm
import tensorflow.keras.backend as K

epochs = 10
lr     = 1e-4

# 记录训练数据,方便后面的分析
history_train_loss     = []
history_train_accuracy = []
history_val_loss       = []
history_val_accuracy   = []

for epoch in range(epochs):
    train_total = len(train_ds)
    val_total   = len(val_ds)
    
    """
    total:预期的迭代数目
    ncols:控制进度条宽度
    mininterval:进度更新最小间隔,以秒为单位(默认值:0.1)
    """
    with tqdm(total=train_total, desc=f'Epoch {epoch + 1}/{epochs}',mininterval=1,ncols=100) as pbar:
        
        lr = lr*0.92
        K.set_value(model.optimizer.lr, lr)

        for image,label in train_ds:   
            """
            训练模型,简单理解train_on_batch就是:它是比model.fit()更高级的一个用法

            想详细了解 train_on_batch 的同学,
            可以看看我的这篇文章:https://www.yuque.com/mingtian-fkmxf/hv4lcq/ztt4gy
            """
            history = model.train_on_batch(image,label)

            train_loss     = history[0]
            train_accuracy = history[1]
            
            pbar.set_postfix({"loss": "%.4f"%train_loss,
                              "accuracy":"%.4f"%train_accuracy,
                              "lr": K.get_value(model.optimizer.lr)})
            pbar.update(1)
        history_train_loss.append(train_loss)
        history_train_accuracy.append(train_accuracy)
            
    print('开始验证!')
    
    with tqdm(total=val_total, desc=f'Epoch {epoch + 1}/{epochs}',mininterval=0.3,ncols=100) as pbar:

        for image,label in val_ds:      
            
            history = model.test_on_batch(image,label)
            
            val_loss     = history[0]
            val_accuracy = history[1]
            
            pbar.set_postfix({"loss": "%.4f"%val_loss,
                              "accuracy":"%.4f"%val_accuracy})
            pbar.update(1)
        history_val_loss.append(val_loss)
        history_val_accuracy.append(val_accuracy)
            
    print('结束验证!')
    print("验证loss为:%.4f"%val_loss)
    print("验证准确率为:%.4f"%val_accuracy)

运行结果:

python 复制代码
Epoch 1/10: 100%|█| 340/340 [01:12<00:00,  4.72it/s, train_loss=0.5849, train_acc=0.6250, lr=9.2e-5]
开始验证!
Epoch 1/10: 100%|██████████████████| 85/85 [00:06<00:00, 12.56it/s, val_loss=0.5191, val_acc=0.6250]
Epoch 2/10:   0%|                                                           | 0/340 [00:00<?, ?it/s]结束验证!
验证loss为:0.5880
验证准确率为:0.5221
Epoch 2/10: 100%|█| 340/340 [01:04<00:00,  5.30it/s, train_loss=0.0058, train_acc=1.0000, lr=8.46e-5
Epoch 2/10:   0%|                                                            | 0/85 [00:00<?, ?it/s]开始验证!
Epoch 2/10: 100%|██████████████████| 85/85 [00:06<00:00, 12.27it/s, val_loss=0.0123, val_acc=1.0000]
Epoch 3/10:   0%|                                                           | 0/340 [00:00<?, ?it/s]结束验证!
验证loss为:0.3964
验证准确率为:0.9074
Epoch 3/10: 100%|█| 340/340 [01:21<00:00,  4.15it/s, train_loss=0.0024, train_acc=1.0000, lr=7.79e-5
开始验证!
Epoch 3/10: 100%|██████████████████| 85/85 [00:07<00:00, 11.98it/s, val_loss=0.0075, val_acc=1.0000]
Epoch 4/10:   0%|                                                           | 0/340 [00:00<?, ?it/s]结束验证!
验证loss为:0.0712
验证准确率为:0.9676
Epoch 4/10: 100%|█| 340/340 [01:04<00:00,  5.28it/s, train_loss=0.0010, train_acc=1.0000, lr=7.16e-5
Epoch 4/10:   0%|                                                            | 0/85 [00:00<?, ?it/s]开始验证!
Epoch 4/10: 100%|██████████████████| 85/85 [00:07<00:00, 12.11it/s, val_loss=0.0009, val_acc=1.0000]
结束验证!
验证loss为:0.0746
验证准确率为:0.9706
Epoch 5/10: 100%|█| 340/340 [01:03<00:00,  5.38it/s, train_loss=0.0034, train_acc=1.0000, lr=6.59e-5
开始验证!
Epoch 5/10: 100%|██████████████████| 85/85 [00:07<00:00, 11.04it/s, val_loss=0.0029, val_acc=1.0000]
结束验证!
验证loss为:0.0350
验证准确率为:0.9897
Epoch 6/10: 100%|█| 340/340 [01:02<00:00,  5.43it/s, train_loss=0.0000, train_acc=1.0000, lr=6.06e-5
Epoch 6/10:   0%|                                                            | 0/85 [00:00<?, ?it/s]开始验证!
Epoch 6/10: 100%|██████████████████| 85/85 [00:07<00:00, 11.08it/s, val_loss=0.0009, val_acc=1.0000]
Epoch 7/10:   0%|                                                           | 0/340 [00:00<?, ?it/s]结束验证!
验证loss为:0.0520
验证准确率为:0.9868
Epoch 7/10: 100%|█| 340/340 [01:21<00:00,  4.15it/s, train_loss=0.0219, train_acc=1.0000, lr=5.58e-5
开始验证!
Epoch 7/10: 100%|██████████████████| 85/85 [00:08<00:00, 10.19it/s, val_loss=0.0050, val_acc=1.0000]
Epoch 8/10:   0%|                                                           | 0/340 [00:00<?, ?it/s]结束验证!
验证loss为:0.0280
验证准确率为:0.9941
Epoch 8/10: 100%|█| 340/340 [01:02<00:00,  5.43it/s, train_loss=0.0003, train_acc=1.0000, lr=5.13e-5
开始验证!
Epoch 8/10: 100%|██████████████████| 85/85 [00:07<00:00, 11.22it/s, val_loss=0.0013, val_acc=1.0000]
结束验证!
验证loss为:0.0374
验证准确率为:0.9868
Epoch 9/10: 100%|█| 340/340 [01:02<00:00,  5.44it/s, train_loss=0.0004, train_acc=1.0000, lr=4.72e-5
Epoch 9/10:   0%|                                                            | 0/85 [00:00<?, ?it/s]开始验证!
Epoch 9/10: 100%|██████████████████| 85/85 [00:07<00:00, 11.24it/s, val_loss=0.0002, val_acc=1.0000]
Epoch 10/10:   0%|                                                          | 0/340 [00:00<?, ?it/s]结束验证!
验证loss为:0.0995
验证准确率为:0.9750
Epoch 10/10: 100%|█| 340/340 [01:22<00:00,  4.15it/s, train_loss=0.0001, train_acc=1.0000, lr=4.34e-
Epoch 10/10:   0%|                                                           | 0/85 [00:00<?, ?it/s]开始验证!
Epoch 10/10: 100%|█████████████████| 85/85 [00:08<00:00, 10.36it/s, val_loss=0.0002, val_acc=1.0000]
结束验证!
验证loss为:0.0219
验证准确率为:0.9941

十、模型评估

python 复制代码
epochs_range = range(epochs)

plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)

plt.plot(epochs_range, history_train_accuracy, label='Training Accuracy')
plt.plot(epochs_range, history_val_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, history_train_loss, label='Training Loss')
plt.plot(epochs_range, history_val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

十一、预测

python 复制代码
import numpy as np

# 采用加载的模型(new_model)来看预测结果
plt.figure(figsize=(18, 3))  # 图形的宽为18高为5
plt.suptitle("预测结果展示")

for images, labels in val_ds.take(1):
    for i in range(8):
        ax = plt.subplot(1,8, i + 1)  
        
        # 显示图片
        plt.imshow(images[i].numpy())
        
        # 需要给图片增加一个维度
        img_array = tf.expand_dims(images[i], 0) 
        
        # 使用模型预测图片中的人物
        predictions = model.predict(img_array)
        plt.title(class_names[np.argmax(predictions)])

        plt.axis("off")

运行结果:

根据代码中bug,修改后运行结果如下:

十二、总结

本周通过tenserflow框架创建VGG16网络模型进行猫狗识别:

VGG16模型结构:

VGG16共包含:

13个卷积层(Convolutional Layer),分别用conv3-XXX表示 (XXX为输出通道数,3代表kernel_size)

3个全连接层(Fully connected Layer),分别用FC-XXXX表示(XXX为输出神经元个数)

5个池化层(Pool layer),分别用maxpool表示。

VGG优缺点分析:

  • VGG优点

VGG的结构非常简洁,整个网络都使用了同样大小的卷积核尺寸(3x3)和最大池化尺寸(2x2)。

  • VGG缺点

1)训练时间过长,调参难度大。2)需要的存储容量大,不利于部署。例如存储VGG-16权重值文件的大小为500多MB,不利于安装到嵌入式系统中。

tqdm是一个强大的工具,它简单易用,高度可定制,适合于各种循环任务,特别是在数据处理和机器学习领域中。通过使用tqdm,开发者可以提供更好的用户体验,准确地展示程序的执行进度。

tqdm的基本特性如下所述:

  • 易用性:tqdm的使用非常简单,通常只需在循环的迭代器上添加tqdm()。只需在 Python 循环中包裹你的迭代器,一行代码就能产生一个精美的进度条。
  • 灵活性:兼容广泛的迭代环境,包括列表、文件、生成器等。它可以和 for 循环、pandas dataframe的 apply 函数以及 Python 的 map 函数等等配合使用。
  • 高效性:对代码的运行效率影响极小。tqdm 使用了智能算法,即使在数据流非常快的情况下,也不会拖慢你的代码速度。
  • 可定制性:允许用户自定义进度条的各种属性,如进度条长度、格式等。
相关推荐
一位小说男主31 分钟前
编码器与解码器:从‘乱码’到‘通话’
人工智能·深度学习
车轮滚滚__1 小时前
uniapp对接unipush 1.0 ios/android
笔记
qq_529025291 小时前
Torch.gather
python·深度学习·机器学习
凯哥是个大帅比2 小时前
人工智能ACA(五)--深度学习基础
人工智能·深度学习
海棠AI实验室2 小时前
AI的进阶之路:从机器学习到深度学习的演变(三)
人工智能·深度学习·机器学习
AIGC大时代3 小时前
如何使用ChatGPT辅助文献综述,以及如何进行优化?一篇说清楚
人工智能·深度学习·chatgpt·prompt·aigc
云边有个稻草人4 小时前
【优选算法】—复写零(双指针算法)
笔记·算法·双指针算法
人机与认知实验室5 小时前
人、机、环境中各有其神经网络系统
人工智能·深度学习·神经网络·机器学习