当前位置:   article > 正文

使用transformer进行图像分类

transformer图像分类

文章目录 

  • 1、导入模型

  • 2、定义加载函数

  • 3、定义批量加载函数

  • 4、加载数据

  • 5、定义数据预处理及训练模型的一些超参数

  • 6、定义数据增强模型

  • 7、构建模型

  • 7.1 构建多层感知器(MLP)

  • 7.2 创建一个类似卷积层的patch层

  • 7.3 查看由patch层随机生成的图像块

  • 7.4构建patch 编码层( encoding layer)

  • 7.5构建ViT模型

  • 8、编译、训练模型

  • 9、查看运行结果


使用Transformer来提升模型的性能
最近几年,Transformer体系结构已成为自然语言处理任务的实际标准,
但其在计算机视觉中的应用还受到限制。在视觉上,注意力要么与卷积网络结合使用,
要么用于替换卷积网络的某些组件,同时将其整体结构保持在适当的位置。2020年10月22日,谷歌人工智能研究院发表一篇题为“An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale”的文章。文章将图像切割成一个个图像块,组成序列化的数据输入Transformer执行图像分类任务。当对大量数据进行预训练并将其传输到多个中型或小型图像识别数据集(如ImageNet、CIFAR-100、VTAB等)时,与目前的卷积网络相比,Vision Transformer(ViT)获得了出色的结果,同时所需的计算资源也大大减少。
这里我们以ViT我模型,实现对数据CiFar10的分类工作,模型性能得到进一步的提升。

1、导入模型

  1. import os
  2. import math
  3. import numpy as np
  4. import pickle as p
  5. import tensorflow as tf
  6. from tensorflow import keras
  7. import matplotlib.pyplot as plt
  8. from tensorflow.keras import layers
  9. import tensorflow_addons as tfa
  10. %matplotlib inline

这里使用了TensorFlow_addons模块,它实现了核心 TensorFlow 中未提供的新功能。
tensorflow_addons的安装要注意与tf的版本对应关系,请参考:
https://github.com/tensorflow/addons。
安装addons时要注意其版本与tensorflow版本的对应,具体关系以上这个链接有。

2、定义加载函数

  1. def load_CIFAR_data(data_dir):
  2. """load CIFAR data"""
  3. images_train=[]
  4. labels_train=[]
  5. for i in range(5):
  6. f=os.path.join(data_dir,'data_batch_%d' % (i+1))
  7. print('loading ',f)
  8. # 调用 load_CIFAR_batch( )获得批量的图像及其对应的标签
  9. image_batch,label_batch=load_CIFAR_batch(f)
  10. images_train.append(image_batch)
  11. labels_train.append(label_batch)
  12. Xtrain=np.concatenate(images_train)
  13. Ytrain=np.concatenate(labels_train)
  14. del image_batch ,label_batch
  15. Xtest,Ytest=load_CIFAR_batch(os.path.join(data_dir,'test_batch'))
  16. print('finished loadding CIFAR-10 data')
  17. # 返回训练集的图像和标签,测试集的图像和标签
  18. return (Xtrain,Ytrain),(Xtest,Ytest)

3、定义批量加载函数

  1. def load_CIFAR_batch(filename):
  2. """ load single batch of cifar """
  3. with open(filename, 'rb')as f:
  4. # 一个样本由标签和图像数据组成
  5. # (3072=32x32x3)
  6. # ...
  7. #
  8. data_dict = p.load(f, encoding='bytes')
  9. images= data_dict[b'data']
  10. labels = data_dict[b'labels']
  11. # 把原始数据结构调整为: BCWH
  12. images = images.reshape(10000, 3, 32, 32)
  13. # tensorflow处理图像数据的结构:BWHC
  14. # 把通道数据C移动到最后一个维度
  15. images = images.transpose (0,2,3,1)
  16. labels = np.array(labels)
  17. return images, labels

4、加载数据

  1. data_dir = r'C:\Users\wumg\jupyter-ipynb\data\cifar-10-batches-py'
  2. (x_train,y_train),(x_test,y_test) = load_CIFAR_data(data_dir)

把数据转换为dataset格式

  1. train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
  2. test_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))

5、定义数据预处理及训练模型的一些超参数

  1. num_classes = 10
  2. input_shape = (32, 32, 3)
  3. learning_rate = 0.001
  4. weight_decay = 0.0001
  5. batch_size = 256
  6. num_epochs = 10
  7. image_size = 72 # We'll resize input images to this size
  8. patch_size = 6 # Size of the patches to be extract from the input images
  9. num_patches = (image_size // patch_size) ** 2
  10. projection_dim = 64
  11. num_heads = 4
  12. transformer_units = [
  13. projection_dim * 2,
  14. projection_dim,
  15. ] # Size of the transformer layers
  16. transformer_layers = 8
  17. mlp_head_units = [2048, 1024] # Size of the dense layers of the final classifier

6、定义数据增强模型

  1. data_augmentation = keras.Sequential(
  2. [
  3. layers.experimental.preprocessing.Normalization(),
  4. layers.experimental.preprocessing.Resizing(image_size, image_size),
  5. layers.experimental.preprocessing.RandomFlip("horizontal"),
  6. layers.experimental.preprocessing.RandomRotation(factor=0.02),
  7. layers.experimental.preprocessing.RandomZoom(
  8. height_factor=0.2, width_factor=0.2
  9. ),
  10. ],
  11. name="data_augmentation",
  12. )
  13. # 使预处理层的状态与正在传递的数据相匹配
  14. #Compute the mean and the variance of the training data for normalization.
  15. data_augmentation.layers[0].adapt(x_train)

预处理层是在模型训练开始之前计算其状态的层。他们在训练期间不会得到更新。大多数预处理层为状态计算实现了adapt()方法。
adapt(data, batch_size=None, steps=None, reset_state=True)该函数参数说明如下:

7、构建模型

7.1 构建多层感知器(MLP)

  1. def mlp(x, hidden_units, dropout_rate):
  2. for units in hidden_units:
  3. x = layers.Dense(units, activation=tf.nn.gelu)(x)
  4. x = layers.Dropout(dropout_rate)(x)
  5. return x

7.2 创建一个类似卷积层的patch层

  1. class Patches(layers.Layer):
  2. def __init__(self, patch_size):
  3. super(Patches, self).__init__()
  4. self.patch_size = patch_size
  5. def call(self, images):
  6. batch_size = tf.shape(images)[0]
  7. patches = tf.image.extract_patches(
  8. images=images,
  9. sizes=[1, self.patch_size, self.patch_size, 1],
  10. strides=[1, self.patch_size, self.patch_size, 1],
  11. rates=[1, 1, 1, 1],
  12. padding="VALID",
  13. )
  14. patch_dims = patches.shape[-1]
  15. patches = tf.reshape(patches, [batch_size, -1, patch_dims])
  16. return patches

7.3 查看由patch层随机生成的图像块

  1. import matplotlib.pyplot as plt
  2. plt.figure(figsize=(4, 4))
  3. image = x_train[np.random.choice(range(x_train.shape[0]))]
  4. plt.imshow(image.astype("uint8"))
  5. plt.axis("off")
  6. resized_image = tf.image.resize(
  7. tf.convert_to_tensor([image]), size=(image_size, image_size)
  8. )
  9. patches = Patches(patch_size)(resized_image)
  10. print(f"Image size: {image_size} X {image_size}")
  11. print(f"Patch size: {patch_size} X {patch_size}")
  12. print(f"Patches per image: {patches.shape[1]}")
  13. print(f"Elements per patch: {patches.shape[-1]}")
  14. n = int(np.sqrt(patches.shape[1]))
  15. plt.figure(figsize=(4, 4))
  16. for i, patch in enumerate(patches[0]):
  17. ax = plt.subplot(n, n, i + 1)
  18. patch_img = tf.reshape(patch, (patch_size, patch_size, 3))
  19. plt.imshow(patch_img.numpy().astype("uint8"))
  20. plt.axis("off")

运行结果
Image size: 72 X 72
Patch size: 6 X 6
Patches per image: 144
Elements per patch: 108

7.4构建patch 编码层( encoding layer)

  1. class PatchEncoder(layers.Layer):
  2. def __init__(self, num_patches, projection_dim):
  3. super(PatchEncoder, self).__init__()
  4. self.num_patches = num_patches
  5. #一个全连接层,其输出维度为projection_dim,没有指明激活函数
  6. self.projection = layers.Dense(units=projection_dim)
  7. #定义一个嵌入层,这是一个可学习的层
  8. #输入维度为num_patches,输出维度为projection_dim
  9. self.position_embedding = layers.Embedding(
  10. input_dim=num_patches, output_dim=projection_dim
  11. )
  12. def call(self, patch):
  13. positions = tf.range(start=0, limit=self.num_patches, delta=1)
  14. encoded = self.projection(patch) + self.position_embedding(positions)
  15. return encoded

7.5构建ViT模型

  1. def create_vit_classifier():
  2. inputs = layers.Input(shape=input_shape)
  3. # Augment data.
  4. augmented = data_augmentation(inputs)
  5. #augmented = augmented_train_batches(inputs)
  6. # Create patches.
  7. patches = Patches(patch_size)(augmented)
  8. # Encode patches.
  9. encoded_patches = PatchEncoder(num_patches, projection_dim)(patches)
  10. # Create multiple layers of the Transformer block.
  11. for _ in range(transformer_layers):
  12. # Layer normalization 1.
  13. x1 = layers.LayerNormalization(epsilon=1e-6)(encoded_patches)
  14. # Create a multi-head attention layer.
  15. attention_output = layers.MultiHeadAttention(
  16. num_heads=num_heads, key_dim=projection_dim, dropout=0.1
  17. )(x1, x1)
  18. # Skip connection 1.
  19. x2 = layers.Add()([attention_output, encoded_patches])
  20. # Layer normalization 2.
  21. x3 = layers.LayerNormalization(epsilon=1e-6)(x2)
  22. # MLP.
  23. x3 = mlp(x3, hidden_units=transformer_units, dropout_rate=0.1)
  24. # Skip connection 2.
  25. encoded_patches = layers.Add()([x3, x2])
  26. # Create a [batch_size, projection_dim] tensor.
  27. representation = layers.LayerNormalization(epsilon=1e-6)(encoded_patches)
  28. representation = layers.Flatten()(representation)
  29. representation = layers.Dropout(0.5)(representation)
  30. # Add MLP.
  31. features = mlp(representation, hidden_units=mlp_head_units, dropout_rate=0.5)
  32. # Classify outputs.
  33. logits = layers.Dense(num_classes)(features)
  34. # Create the Keras model.
  35. model = keras.Model(inputs=inputs, outputs=logits)
  36. return model

该模型的处理流程如下图所示

8、编译、训练模型

  1. def run_experiment(model):
  2. optimizer = tfa.optimizers.AdamW(
  3. learning_rate=learning_rate, weight_decay=weight_decay
  4. )
  5. model.compile(
  6. optimizer=optimizer,
  7. loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
  8. metrics=[
  9. keras.metrics.SparseCategoricalAccuracy(name="accuracy"),
  10. keras.metrics.SparseTopKCategoricalAccuracy(5, name="top-5-accuracy"),
  11. ],
  12. )
  13. #checkpoint_filepath = r".\tmp\checkpoint"
  14. checkpoint_filepath ="model_bak.hdf5"
  15. checkpoint_callback = keras.callbacks.ModelCheckpoint(
  16. checkpoint_filepath,
  17. monitor="val_accuracy",
  18. save_best_only=True,
  19. save_weights_only=True,
  20. )
  21. history = model.fit(
  22. x=x_train,
  23. y=y_train,
  24. batch_size=batch_size,
  25. epochs=num_epochs,
  26. validation_split=0.1,
  27. callbacks=[checkpoint_callback],
  28. )
  29. model.load_weights(checkpoint_filepath)
  30. _, accuracy, top_5_accuracy = model.evaluate(x_test, y_test)
  31. print(f"Test accuracy: {round(accuracy * 100, 2)}%")
  32. print(f"Test top 5 accuracy: {round(top_5_accuracy * 100, 2)}%")
  33. return history

实例化类,运行模型

  1. vit_classifier = create_vit_classifier()
  2. history = run_experiment(vit_classifier)

运行结果
Epoch 1/10
176/176 [==============================] - 68s 333ms/step - loss: 2.6394 - accuracy: 0.2501 - top-5-accuracy: 0.7377 - val_loss: 1.5331 - val_accuracy: 0.4580 - val_top-5-accuracy: 0.9092
Epoch 2/10
176/176 [==============================] - 58s 327ms/step - loss: 1.6359 - accuracy: 0.4150 - top-5-accuracy: 0.8821 - val_loss: 1.2714 - val_accuracy: 0.5348 - val_top-5-accuracy: 0.9464
Epoch 3/10
176/176 [==============================] - 58s 328ms/step - loss: 1.4332 - accuracy: 0.4839 - top-5-accuracy: 0.9210 - val_loss: 1.1633 - val_accuracy: 0.5806 - val_top-5-accuracy: 0.9616
Epoch 4/10
176/176 [==============================] - 58s 329ms/step - loss: 1.3253 - accuracy: 0.5280 - top-5-accuracy: 0.9349 - val_loss: 1.1010 - val_accuracy: 0.6112 - val_top-5-accuracy: 0.9572
Epoch 5/10
176/176 [==============================] - 58s 330ms/step - loss: 1.2380 - accuracy: 0.5626 - top-5-accuracy: 0.9411 - val_loss: 1.0212 - val_accuracy: 0.6400 - val_top-5-accuracy: 0.9690
Epoch 6/10
176/176 [==============================] - 58s 330ms/step - loss: 1.1486 - accuracy: 0.5945 - top-5-accuracy: 0.9520 - val_loss: 0.9698 - val_accuracy: 0.6602 - val_top-5-accuracy: 0.9718
Epoch 7/10
176/176 [==============================] - 58s 330ms/step - loss: 1.1208 - accuracy: 0.6060 - top-5-accuracy: 0.9558 - val_loss: 0.9215 - val_accuracy: 0.6724 - val_top-5-accuracy: 0.9790
Epoch 8/10
176/176 [==============================] - 58s 330ms/step - loss: 1.0643 - accuracy: 0.6248 - top-5-accuracy: 0.9621 - val_loss: 0.8709 - val_accuracy: 0.6944 - val_top-5-accuracy: 0.9768
Epoch 9/10
176/176 [==============================] - 58s 330ms/step - loss: 1.0119 - accuracy: 0.6446 - top-5-accuracy: 0.9640 - val_loss: 0.8290 - val_accuracy: 0.7142 - val_top-5-accuracy: 0.9784
Epoch 10/10
176/176 [==============================] - 58s 330ms/step - loss: 0.9740 - accuracy: 0.6615 - top-5-accuracy: 0.9666 - val_loss: 0.8175 - val_accuracy: 0.7096 - val_top-5-accuracy: 0.9806
313/313 [==============================] - 9s 27ms/step - loss: 0.8514 - accuracy: 0.7032 - top-5-accuracy: 0.9773
Test accuracy: 70.32%
Test top 5 accuracy: 97.73%
In [15]:
从结果看可以来看,测试精度已达70%,这是一个较大提升!

9、查看运行结果

  1. acc = history.history['accuracy']
  2. val_acc = history.history['val_accuracy']
  3. loss = history.history['loss']
  4. val_loss =history.history['val_loss']
  5. plt.figure(figsize=(8, 8))
  6. plt.subplot(2, 1, 1)
  7. plt.plot(acc, label='Training Accuracy')
  8. plt.plot(val_acc, label='Validation Accuracy')
  9. plt.legend(loc='lower right')
  10. plt.ylabel('Accuracy')
  11. plt.ylim([min(plt.ylim()),1.1])
  12. plt.title('Training and Validation Accuracy')
  13. plt.subplot(2, 1, 2)
  14. plt.plot(loss, label='Training Loss')
  15. plt.plot(val_loss, label='Validation Loss')
  16. plt.legend(loc='upper right')
  17. plt.ylabel('Cross Entropy')
  18. plt.ylim([-0.1,4.0])
  19. plt.title('Training and Validation Loss')
  20. plt.xlabel('epoch')
  21. plt.show()

运行结果

作者 :吴茂贵,资深大数据和人工智能技术专家,在BI、数据挖掘与分析、数据仓库、机器学习等领域工作超过20年!在基于Spark、TensorFlow、Pytorch、Keras等机器学习和深度学习方面有大量的工程实践经验。代表作有《深入浅出Embedding:原理解析与应用实践》、《Python深度学习基于Pytorch》和《Python深度学习基于TensorFlow》。

——The  End——

点击购买

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/92889
推荐阅读
相关标签
  

闽ICP备14008679号