TensorFlow2实战 | 第7周:咖啡豆识别

我的环境

  • 言语环境:Python3.10.11
  • 编译器:Jupyter Notebook
  • 深度学习框架:TensorFlow2.4.1
  • 显卡(GPU):NVIDIA GeForce RTX 4070

相关教程

  • 编译器教程:【新手入门深度学习 | 1-2:编译器Jupyter Notebook】
  • 深度学习环境装备教程:【新手入门深度学习 | 1-1:装备深度学习环境】
  • 一个深度学习小白需求的一切材料我都放这儿了:【新手入门深度学习 | 目录】

建议你学习本文之前先看看下面这篇入门文章,以便你能够更好的了解本文: 新手入门深度学习 | 2-1:图画数据建模流程示例

强烈建议咱们运用Jupyter Notebook编译器打开源码,你接下来的操作将会十分便捷的!

  • 假如你是深度学习小白,阅读本文前建议先学习一下 《新手入门深度学习》
  • 假如你有必定基础,但是缺少实战经验,可经过 《深度学习100例》 补齐基础
  • 别的,咱们正在经过 365天深度学习练习营 抱团学习,营内为咱们供给体系的学习教案专业的指导十分良好的学习氛围,欢迎你的加入

一、前期工作

1. 设置GPU

假如运用的是CPU能够疏忽这步

import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")
if gpus:
    tf.config.experimental.set_memory_growth(gpus[0], True)  #设置GPU显存用量按需运用
    tf.config.set_visible_devices([gpus[0]],"GPU")

2. 导入数据

from tensorflow       import keras
from tensorflow.keras import layers,models
import numpy             as np
import matplotlib.pyplot as plt
import os,PIL,pathlib
data_dir = "./49-data/"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*.png')))
print("图片总数为:",image_count)
图片总数为: 1200

二、数据预处理

1. 加载数据

运用image_dataset_from_directory办法将磁盘中的数据加载到tf.data.Dataset

batch_size = 32
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=123,
    image_size=(img_height, img_width),
    batch_size=batch_size)
Found 1200 files belonging to 4 classes.
Using 960 files for training.
"""
关于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=123,
    image_size=(img_height, img_width),
    batch_size=batch_size)
Found 1200 files belonging to 4 classes.
Using 240 files for validation.

咱们能够经过class_names输出数据集的标签。标签将按字母次序对应于目录称号。

class_names = train_ds.class_names
print(class_names)
['Dark', 'Green', 'Light', 'Medium']

2. 可视化数据

plt.figure(figsize=(10, 4))  # 图形的宽为10高为5
for images, labels in train_ds.take(1):
    for i in range(10):
        ax = plt.subplot(2, 5, i + 1)  
        plt.imshow(images[i].numpy().astype("uint8"))
        plt.title(class_names[labels[i]])
        plt.axis("off")

TensorFlow2实战 | 第7周:咖啡豆识别

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

3. 装备数据集

  • shuffle() :打乱数据,关于此函数的具体介绍能够参阅:zhuanlan.zhihu.com/p/42417456
  • prefetch() :预取数据,加速运行,其具体介绍能够参阅我前两篇文章,里面都有解说。
  • cache() :将数据集缓存到内存当中,加速运行
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds   = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
normalization_layer = layers.experimental.preprocessing.Rescaling(1./255)
train_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
val_ds   = val_ds.map(lambda x, y: (normalization_layer(x), y))
image_batch, labels_batch = next(iter(val_ds))
first_image = image_batch[0]
# 检查归一化后的数据
print(np.min(first_image), np.max(first_image))
0.0 1.0

三、构建VGG-16网络

在官方模型与自建模型之间进行二选一就能够了,选着一个注释掉别的一个。

VGG优缺陷分析:

  • VGG长处

VGG的结构十分简洁,整个网络都运用了相同巨细的卷积核尺度(3x3)和最大池化尺度(2x2)

  • VGG缺陷

1)练习时刻过长,调参难度大。2)需求的存储容量大,不利于布置。例如存储VGG-16权重值文件的巨细为500多MB,不利于安装到嵌入式体系中。

1. 官方模型

官网模型调用这块我放到后面几篇文章中,下面主要讲一下VGG-16

# model = tf.keras.applications.VGG16(weights='imagenet')
# model.summary()

2. 自建模型

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(len(class_names), (img_width, img_height, 3))
model.summary()
Model: "model"
_________________________________________________________________
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, 4)                 16388     
=================================================================
Total params: 134,276,932
Trainable params: 134,276,932
Non-trainable params: 0
_________________________________________________________________

3. 网络结构图

参加了365天深度学习练习营的同学能够在语雀中检查网络结构图

关于卷积的相关知识能够参阅文章:mtyjkh.blog.csdn.net/article/det…

结构说明:

  • 13个卷积层(Convolutional Layer),分别用blockX_convX表明
  • 3个全连接层(Fully connected Layer),分别用fcXpredictions表明
  • 5个池化层(Pool layer),分别用blockX_pool表明

VGG-16包含了16个躲藏层(13个卷积层和3个全连接层),故称为VGG-16

四、编译

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

  • 丢失函数(loss):用于衡量模型在练习期间的准确率。
  • 优化器(optimizer):决议模型如何根据其看到的数据和自身的丢失函数进行更新。
  • 目标(metrics):用于监控练习和测试过程。以下示例运用了准确率,即被正确分类的图画的比率。
# 设置初始学习率
initial_learning_rate = 1e-4
lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
        initial_learning_rate, 
        decay_steps=30,      # 敲黑板!!!这儿是指 steps,不是指epochs
        decay_rate=0.92,     # lr经过一次衰减就会变成 decay_rate*lr
        staircase=True)
# 设置优化器
opt = tf.keras.optimizers.Adam(learning_rate=initial_learning_rate)
model.compile(optimizer=opt,
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

五、练习模型

epochs = 20
history = model.fit(
    train_ds,
    validation_data=val_ds,
    epochs=epochs
)
Epoch 1/20
30/30 [==============================] - 13s 187ms/step - loss: 1.3438 - accuracy: 0.3208 - val_loss: 0.9648 - val_accuracy: 0.6750
Epoch 2/20
30/30 [==============================] - 4s 139ms/step - loss: 0.7589 - accuracy: 0.6052 - val_loss: 0.6280 - val_accuracy: 0.7375
Epoch 3/20
30/30 [==============================] - 4s 136ms/step - loss: 0.6868 - accuracy: 0.6292 - val_loss: 0.7508 - val_accuracy: 0.5125
Epoch 4/20
30/30 [==============================] - 4s 136ms/step - loss: 0.6073 - accuracy: 0.6927 - val_loss: 0.6004 - val_accuracy: 0.5875
 ......
Epoch 18/20
30/30 [==============================] - 4s 137ms/step - loss: 0.0537 - accuracy: 0.9781 - val_loss: 0.1639 - val_accuracy: 0.9667
Epoch 19/20
30/30 [==============================] - 4s 138ms/step - loss: 0.0580 - accuracy: 0.9781 - val_loss: 0.1093 - val_accuracy: 0.9625
Epoch 20/20
30/30 [==============================] - 4s 136ms/step - loss: 0.0765 - accuracy: 0.9740 - val_loss: 0.1346 - val_accuracy: 0.9667

六、模型评估

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

TensorFlow2实战 | 第7周:咖啡豆识别

  • 本文为365天深度学习练习营 中的学习记载博客