卷积神经网络(CNN)识别神奇宝贝小智一伙

一、前言

我的环境:

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

往期精彩内容:

来自专栏:机器学习与深度学习算法推荐

二、前期工作

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. 导入数据

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

import os,PIL

# 设置随机种子尽可能使结果可以重现
import numpy as np
np.random.seed(1)

# 设置随机种子尽可能使结果可以重现
import tensorflow as tf
tf.random.set_seed(1)

import pathlib
data_dir = "Pokemon"
data_dir = pathlib.Path(data_dir)

3. 查看数据

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

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

二、数据预处理

1.加载数据

batch_size = 8
img_height = 224
img_width = 224

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

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)
Found 219 files belonging to 10 classes.
Using 176 files for training.
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)
Found 219 files belonging to 10 classes.
Using 43 files for validation.

我们可以通过class_names输出数据集的标签。标签将按字母顺序对应于目录名称。

class_names = train_ds.class_names
print(class_names)
['Alcremie', 'Eevee', 'Furfrou', 'Kyurem', 'Minior', 'Pikachu', 'Rotom', 'Squirtle', 'Vivillon', 'Zygarde']

2. 可视化数据

plt.figure(figsize=(10, 5))  # 图形的宽为10高为5
plt.suptitle("数据展示")

for images, labels in train_ds.take(1):
    for i in range(8):
        
        ax = plt.subplot(2, 4, i + 1)  
        
        ax.patch.set_facecolor('yellow')
        
        plt.imshow(images[i].numpy().astype("uint8"))
        plt.title(class_names[labels[i]])
        
        plt.axis("off")

在这里插入图片描述

  1. 再次检查数据
for image_batch, labels_batch in train_ds:
    print(image_batch.shape)
    print(labels_batch.shape)
    break
(8, 224, 224, 3)
(8,)
  • Image_batch是形状的张量(8, 224, 224, 3)。这是一批形状240x240x3的8张图片(最后一维指的是彩色通道RGB)。
  • Label_batch是形状(8,)的张量,这些标签对应8张图片

4. 配置数据集

AUTOTUNE = tf.data.AUTOTUNE

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

三、调用官方网络模型

tf.keras.applications API地址:https://www.tensorflow.org/api_docs/python/tf/keras/applications

接口示例:VGG-16官方模型接口

# 这是函数原型,请勿运行该代码
tf.keras.applications.vgg16.VGG16(
    include_top=True, weights='imagenet', input_tensor=None,
    input_shape=None, pooling=None, classes=1000,
    classifier_activation='softmax'
)
<tensorflow.python.keras.engine.functional.Functional at 0x220df3e35f8>

常用的三个参数解释如下:

  • include_top:是否包括网络顶部的 3 个全连接层。
  • weights:默认不加载权重文件,"imagenet"加载官方权重文件,或者输入自己的权重文件路径。
  • classes:分类图像的类别数

其他参数暂时不建议大家了解,模型接口都是非常相似的,大家可以从上面的众多模型中选择自己想要的调用,接口函数如下:

  1. tf.keras.applications.xception.Xception()
  2. tf.keras.applications.vgg16.VGG16()
  3. tf.keras.applications.vgg19.VGG19()
  4. tf.keras.applications.resnet50.ResNet50()
  5. tf.keras.applications.inception_v3.InceptionV3()
  6. tf.keras.applications.inception_resnet_v2.InceptionResNetV2()
  7. tf.keras.applications.mobilenet.MobileNet()
  8. tf.keras.applications.mobilenet_v2.MobileNetV2()
  9. tf.keras.applications.densenet.DenseNet121()
  10. tf.keras.applications.densenet.DenseNet169()
  11. tf.keras.applications.densenet.DenseNet201()
  12. tf.keras.applications.nasnet.NASNetMobile()
  13. tf.keras.applications.nasnet.NASNetLarge()
model = tf.keras.applications.DenseNet121(weights='imagenet')
model.summary()

四、设置动态学习率

这里先罗列一下学习率大与学习率小的优缺点。

  • 学习率大
    • 优点: 1、加快学习速率。 2、有助于跳出局部最优值。
    • 缺点: 1、导致模型训练不收敛。 2、单单使用大学习率容易导致模型不精确。
  • 学习率小
    • 优点: 1、有助于模型收敛、模型细化。 2、提高模型精度。
    • 缺点: 1、很难跳出局部最优值。 2、收敛缓慢。

注意:这里设置的动态学习率为:指数衰减型(ExponentialDecay)。在每一个epoch开始前,学习率(learning_rate)都将会重置为初始学习率(initial_learning_rate),然后再重新开始衰减。计算公式如下:

learning_rate = initial_learning_rate * decay_rate ^ (step / decay_steps)

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

lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
        initial_learning_rate, 
        decay_steps=5,      # 敲黑板!!!这里是指 steps,不是指epochs
        decay_rate=0.96,     # lr经过一次衰减就会变成 decay_rate*lr
        staircase=True)

# 将指数衰减学习率送入优化器
optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule)

五、编译

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

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

六、训练模型

epochs = 20

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

七、模型评估

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

八、保存and加载模型

这是最简单的模型保存与加载方法哈

# 保存模型
model.save('model/16_model.h5')
# 加载模型
new_model = tf.keras.models.load_model('model/16_model.h5')

九、预测

九、预测
# 采用加载的模型(new_model)来看预测结果

plt.figure(figsize=(10, 5))  # 图形的宽为10高为5
plt.suptitle("预测结果展示")

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

        plt.axis("off")

在这里插入图片描述

深度学习之卷积神经网络CNN做手写体识别的VS代码。支持linux版本和VS2012版本。 tiny-cnn: A C++11 implementation of convolutional neural networks ======== tiny-cnn is a C++11 implementation of convolutional neural networks. design principle ----- * fast, without GPU 98.8% accuracy on MNIST in 13 minutes training (@Core i7-3520M) * header only, policy-based design supported networks ----- ### layer-types * fully-connected layer * convolutional layer * average pooling layer ### activation functions * tanh * sigmoid * rectified linear * identity ### loss functions * cross-entropy * mean-squared-error ### optimization algorithm * stochastic gradient descent (with/without L2 normalization) * stochastic gradient levenberg marquardt dependencies ----- * boost C++ library * Intel TBB sample code ------ ```cpp #include "tiny_cnn.h" using namespace tiny_cnn; // specify loss-function and optimization-algorithm typedef network CNN; // tanh, 32x32 input, 5x5 window, 1-6 feature-maps convolution convolutional_layer C1(32, 32, 5, 1, 6); // tanh, 28x28 input, 6 feature-maps, 2x2 subsampling average_pooling_layer S2(28, 28, 6, 2); // fully-connected layers fully_connected_layer F3(14*14*6, 120); fully_connected_layer F4(120, 10); // connect all CNN mynet; mynet.add(&C1); mynet.add(&S2); mynet.add(&F3); mynet.add(&F4); assert(mynet.in_dim() == 32*32); assert(mynet.out_dim() == 10); ``` more sample, read main.cpp build sample program ------ ### gcc(4.6~) without tbb ./waf configure --BOOST_ROOT=your-boost-root ./waf build with tbb ./waf configure --TBB --TBB_ROOT=your-tbb-root --BOOST_ROOT=your-boost-root ./waf build with tbb and SSE/AVX ./waf configure --AVX --TBB --TBB_ROOT=your-tbb-root --BOOST_ROOT=your-boost-root ./waf build ./waf configure --SSE --TBB --TBB_ROOT=your-tbb-root --BOOST_ROOT=your-boost-root ./waf build or edit inlude/config.h to customize default behavior. ### vc(2012~) open vc/tiny_cnn.sln and build in release mode.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NoteLoopy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值