5天学习计划 第7周:咖啡豆识别_jie

前期工作

本文为365天深度学习训练营内部限免文章
参考本文所写记录性文章,请在文章开头保留以下内容

  • 本文为365天深度学习训练营 中的学习记录博客
  • 参考文章:365天深度学习训练营-第7周:咖啡豆识别(训练营内部成员可读)
  • 原作者:K同学啊|接辅导、项目定制

我的环境:

  • 语言环境:Python3.6.5
  • 编译器:jupyter lab
  • 深度学习环境:TensorFlow2.4.1

⏲往期文章:

  • 5天学习计划-第6周:好莱坞明星识别

  • 5天学习计划-第5周:运动鞋品牌识别

  • 难度:夯实基础

  • 语言:Python3、TensorFlow2

  • 时间:9月5-9月9日

要求:

  1. 自己搭建VGG-16网络框架
  2. 调用官方的VGG-16网络框架

拔高(可选):

  1. 验证集准确率达到100%
  2. 使用PPT画出VGG-16算法框架图(发论文需要这项技能)

探索(难度有点大)

  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")

导入数据

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
import torch
import torch.nn as nn
import os,PIL,pathlib
from PIL import Image
from torchvision import transforms, datasets
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

数据预处理

加载数据

使用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']

可视化数据

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")

5天学习计划 第7周:咖啡豆识别_jie_第1张图片

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() :将数据集缓存到内存当中,加速运行
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,不利于安装到嵌入式系统中。

官方模型

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

from tensorflow.keras.models import Model
from tensorflow.keras.applications import VGG16
from tensorflow.keras.layers import Flatten, Dense

NUM_CLASSES = len(class_names)
model = tf.keras.applications.VGG16(include_top=False,weights='imagenet',input_shape=(224, 224, 3))
x = model.output
# 分类
x = Flatten(name='flatten')(x)
x = Dense(512, activation='relu', name='fc1-')(x)
x = Dense(128, activation='relu', name='fc2-')(x)
x = Dense(NUM_CLASSES, activation='softmax', name='predictions')(x)
model = Model(model.input, x, name="My-VGG16")
model.summary()
Model: "My-VGG16"
_________________________________________________________________
 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, 512)               12845568  
                                                                 
 fc2- (Dense)                (None, 128)               65664     
                                                                 
 predictions (Dense)         (None, 4)                 516       
                                                                 
=================================================================
Total params: 27,626,436
Trainable params: 27,626,436
Non-trainable params: 0
_________________________________________________________________

自建模型

# 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()
2022-09-09 18:18:38.287389: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 411041792 exceeds 10% of free system memory.


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
_________________________________________________________________


2022-09-09 18:18:38.623610: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 411041792 exceeds 10% of free system memory.
2022-09-09 18:18:38.650108: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 411041792 exceeds 10% of free system memory.

网络结构图

参加了365天深度学习训练营的同学可以在语雀中查看网络结构图

VGG-16的结构说明:

● 13个卷积层(Convolutional Layer),分别用blockX_convX表示

● 3个全连接层(Fully connected Layer),分别用fcX与predictions表示

● 5个池化层(Pool layer),分别用blockX_pool表示

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

自己画的结构图
5天学习计划 第7周:咖啡豆识别_jie_第2张图片


编译

设置初始学习率

# 设置初始学习率
initial_learning_rate = 1e-4

lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
        initial_learning_rate, 
        decay_steps=30,      # 敲黑板!!!这里是指 steps,不是指epochs
        decay_rate=0.99,     # 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'])

设置早停

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

from tensorflow.keras.callbacks import ModelCheckpoint,EarlyStopping

checkpointer = ModelCheckpoint('best_model2.h5',
                               monitor='val_accuracy',
                               verbose=1,
                               save_best_only=True,
                               save_weights_only=True)

earlystopper = EarlyStopping(monitor='val_accuracy',
                             min_delta=0.001,
                             patience=10,
                             verbose=1     )

训练模型

epochs = 14

history = model.fit(train_ds,validation_data=val_ds,
          epochs=epochs,callbacks=[checkpointer,earlystopper])
Epoch 1/14


/home/liangjie/anaconda3/lib/python3.9/site-packages/keras/backend.py:5581: UserWarning: "`sparse_categorical_crossentropy` received `from_logits=True`, but the `output` argument was produced by a Softmax activation and thus does not represent logits. Was this intended?
  output, from_logits = _get_logits(
2022-09-10 07:06:04.530289: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 411041792 exceeds 10% of free system memory.
2022-09-10 07:06:04.677350: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 411041792 exceeds 10% of free system memory.
2022-09-10 07:06:05.129971: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 205520896 exceeds 10% of free system memory.
2022-09-10 07:06:05.163211: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 205520896 exceeds 10% of free system memory.
2022-09-10 07:06:10.731038: W tensorflow/core/framework/cpu_allocator_impl.cc:82] Allocation of 205520896 exceeds 10% of free system memory.


30/30 [==============================] - ETA: 0s - loss: 0.7320 - accuracy: 0.6677
Epoch 1: val_accuracy improved from -inf to 0.91667, saving model to best_model2.h5
30/30 [==============================] - 267s 9s/step - loss: 0.7320 - accuracy: 0.6677 - val_loss: 0.2218 - val_accuracy: 0.9167
Epoch 2/14
30/30 [==============================] - ETA: 0s - loss: 0.1085 - accuracy: 0.9635
Epoch 2: val_accuracy improved from 0.91667 to 0.95833, saving model to best_model2.h5
30/30 [==============================] - 262s 9s/step - loss: 0.1085 - accuracy: 0.9635 - val_loss: 0.1196 - val_accuracy: 0.9583
Epoch 3/14
30/30 [==============================] - ETA: 0s - loss: 0.1225 - accuracy: 0.9552
Epoch 3: val_accuracy did not improve from 0.95833
30/30 [==============================] - 261s 9s/step - loss: 0.1225 - accuracy: 0.9552 - val_loss: 0.3096 - val_accuracy: 0.8917
Epoch 4/14
30/30 [==============================] - ETA: 0s - loss: 0.0507 - accuracy: 0.9823
Epoch 4: val_accuracy improved from 0.95833 to 0.99167, saving model to best_model2.h5
30/30 [==============================] - 261s 9s/step - loss: 0.0507 - accuracy: 0.9823 - val_loss: 0.0328 - val_accuracy: 0.9917
Epoch 5/14
30/30 [==============================] - ETA: 0s - loss: 0.1811 - accuracy: 0.9396
Epoch 5: val_accuracy did not improve from 0.99167
30/30 [==============================] - 260s 9s/step - loss: 0.1811 - accuracy: 0.9396 - val_loss: 0.1274 - val_accuracy: 0.9542
Epoch 6/14
30/30 [==============================] - ETA: 0s - loss: 0.0752 - accuracy: 0.9760
Epoch 6: val_accuracy did not improve from 0.99167
30/30 [==============================] - 261s 9s/step - loss: 0.0752 - accuracy: 0.9760 - val_loss: 0.1186 - val_accuracy: 0.9792
Epoch 7/14
30/30 [==============================] - ETA: 0s - loss: 0.0767 - accuracy: 0.9677
Epoch 7: val_accuracy did not improve from 0.99167
30/30 [==============================] - 259s 9s/step - loss: 0.0767 - accuracy: 0.9677 - val_loss: 0.0747 - val_accuracy: 0.9708
Epoch 8/14
30/30 [==============================] - ETA: 0s - loss: 0.0149 - accuracy: 0.9969
Epoch 8: val_accuracy did not improve from 0.99167
30/30 [==============================] - 262s 9s/step - loss: 0.0149 - accuracy: 0.9969 - val_loss: 0.0277 - val_accuracy: 0.9875
Epoch 9/14
30/30 [==============================] - ETA: 0s - loss: 0.0020 - accuracy: 1.0000
Epoch 9: val_accuracy improved from 0.99167 to 1.00000, saving model to best_model2.h5
30/30 [==============================] - 263s 9s/step - loss: 0.0020 - accuracy: 1.0000 - val_loss: 0.0027 - val_accuracy: 1.0000
Epoch 10/14
30/30 [==============================] - ETA: 0s - loss: 2.2677e-04 - accuracy: 1.0000
Epoch 10: val_accuracy did not improve from 1.00000
30/30 [==============================] - 259s 9s/step - loss: 2.2677e-04 - accuracy: 1.0000 - val_loss: 0.0018 - val_accuracy: 1.0000
Epoch 11/14
30/30 [==============================] - ETA: 0s - loss: 1.1921e-04 - accuracy: 1.0000
Epoch 11: val_accuracy did not improve from 1.00000
30/30 [==============================] - 259s 9s/step - loss: 1.1921e-04 - accuracy: 1.0000 - val_loss: 0.0014 - val_accuracy: 1.0000
Epoch 12/14
30/30 [==============================] - ETA: 0s - loss: 7.9640e-05 - accuracy: 1.0000
Epoch 12: val_accuracy did not improve from 1.00000
30/30 [==============================] - 258s 9s/step - loss: 7.9640e-05 - accuracy: 1.0000 - val_loss: 9.7935e-04 - val_accuracy: 1.0000
Epoch 13/14
30/30 [==============================] - ETA: 0s - loss: 5.4854e-05 - accuracy: 1.0000
Epoch 13: val_accuracy did not improve from 1.00000
30/30 [==============================] - 259s 9s/step - loss: 5.4854e-05 - accuracy: 1.0000 - val_loss: 6.7156e-04 - val_accuracy: 1.0000
Epoch 14/14
30/30 [==============================] - ETA: 0s - loss: 3.8973e-05 - accuracy: 1.0000
Epoch 14: val_accuracy did not improve from 1.00000
30/30 [==============================] - 258s 9s/step - loss: 3.8973e-05 - accuracy: 1.0000 - val_loss: 5.2667e-04 - val_accuracy: 1.0000

可视化结果

from pyecharts.charts import *
import pyecharts.options as opts
from pyecharts.globals import ThemeType
loss = history.history['loss']
val_loss = history.history['val_loss']
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
line_loss = Line()
line_loss.add_xaxis([i for i in range(20)])
line_loss.add_yaxis('loss', loss, label_opts=opts.LabelOpts(is_show=False))
line_loss.add_yaxis('val_loss', val_loss, label_opts=opts.LabelOpts(is_show=False))
line_loss.set_global_opts(legend_opts=opts.LegendOpts(pos_top='5%',pos_left='20%'),
                    tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="line"))

line_acc = Line()
line_acc.add_xaxis([i for i in range(20)])
line_acc.add_yaxis('accuracy', acc, label_opts=opts.LabelOpts(is_show=False))
line_acc.add_yaxis('val_accuracy', val_acc, label_opts=opts.LabelOpts(is_show=False))
line_acc.set_global_opts(title_opts=opts.TitleOpts('模型训练过程效果记录', pos_left='center'),
                    legend_opts=opts.LegendOpts(pos_top='5%', pos_left='65%'),
                    yaxis_opts=opts.AxisOpts(is_scale=True),
                    tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="line"))

grid = Grid(init_opts=opts.InitOpts(theme=ThemeType.CHALK))
grid.add(line_loss,grid_opts=opts.GridOpts(pos_left='5%', pos_right='55%'))
grid.add(line_acc,grid_opts=opts.GridOpts(pos_left='55%', pos_right='5%'))
grid.render_notebook()

5天学习计划 第7周:咖啡豆识别_jie_第3张图片

    
# 模型的评估
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

loss = history.history['loss']
val_loss = history.history['val_loss']

epochs_range = range(len(loss))

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()

5天学习计划 第7周:咖啡豆识别_jie_第4张图片

总结

源代码基础上,修改了哪些

设置了早停,epochs从20减少到14;利用VGG官方模型

有哪些改进

源代码结果:5天学习计划 第7周:咖啡豆识别_jie_第5张图片

改进后的效果:5天学习计划 第7周:咖啡豆识别_jie_第6张图片

修改结果前:val_accuracy: 0.96

修改结果后:val_accuracy: 1.00

你可能感兴趣的:(学习,tensorflow,深度学习)