T10周:数据增强
- **一、前期工作**
- 1.设置GPU,导入库
- 2.加载数据
- **二、数据增强**
- **三、增强方式**
- 方法一:将其嵌入model中
- 方法二:在Dataset数据集中进行数据增强
- **四、训练模型**
- **五、自定义增强函数**
- **六、总结**
- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊
🍺 要求:
- 学会在代码中使用数据增强手段来提高acc
- 请探索更多的数据增强手段并记录
在本教程中,你将学会如何进行数据增强,并通过数据增强用少量数据达到非常非常棒的识别准确率。我将展示两种数据增强方式,以及如何自定义数据增强方式并将其放到我们代码当中,两种数据增强方式如下:
- 将数据增强模块嵌入model中
- 在Dataset数据集中进行数据增强
⌛ 我的环境:
- 语言环境:Python3.6.5
- 编译器:Google Colab
- 深度学习环境:TensorFlow2.17.0
一、前期工作
1.设置GPU,导入库
import matplotlib.pyplot as plt
import numpy as np
#隐藏警告
import warnings
warnings.filterwarnings('ignore')
from tensorflow.keras import layers
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")
# 打印显卡信息,确认GPU可用
print(gpus)
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
2.加载数据
from google.colab import drive
drive.mount("/content/drive/")
%cd "/content/drive/Othercomputers/My laptop/jupyter notebook/data/"
Mounted at /content/drive/
/content/drive/Othercomputers/My laptop/jupyter notebook/data
data_dir = "./10/"
img_height = 224
img_width = 224
batch_size = 32
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.3,
subset="training",
seed=12,
image_size=(img_height, img_width),
batch_size=batch_size)
Found 600 files belonging to 2 classes.
Using 420 files for training.
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.3,
subset="validation",
seed=12,
image_size=(img_height, img_width),
batch_size=batch_size)
Found 600 files belonging to 2 classes.
Using 180 files for validation.
由于原始数据集不包含测试集,因此需要创建一个。使用 tf.data.experimental.cardinality
确定验证集中有多少批次的数据,然后将其中的 20% 移至测试集。
val_batches = tf.data.experimental.cardinality(val_ds)
test_ds = val_ds.take(val_batches // 5)
val_ds = val_ds.skip(val_batches // 5)
print('Number of validation batches: %d' % tf.data.experimental.cardinality(val_ds))
print('Number of test batches: %d' % tf.data.experimental.cardinality(test_ds))
Number of validation batches: 5
Number of test batches: 1
class_names = train_ds.class_names
print(class_names)
['cat', 'dog']
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)
test_ds = test_ds.map(preprocess_image, num_parallel_calls=AUTOTUNE)
train_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
plt.figure(figsize=(15, 10)) # 图形的宽为15高为10
for images, labels in train_ds.take(1):
for i in range(8):
ax = plt.subplot(2, 4, i + 1)
plt.imshow(images[i])
plt.title(class_names[labels[i]])
plt.axis("off")
二、数据增强
我们可以使用 tf.keras.layers.experimental.preprocessing.RandomFlip
与 tf.keras.layers.experimental.preprocessing.RandomRotation
进行数据增强
tf.keras.layers.experimental.preprocessing.RandomFlip
:水平和垂直随机翻转每个图像。tf.keras.layers.experimental.preprocessing.RandomRotation
:随机旋转每个图像
data_augmentation = tf.keras.Sequential([
tf.keras.layers.RandomFlip("horizontal_and_vertical"), #进行随机水平和垂直翻转
tf.keras.layers.RandomRotation(0.2), #按照0.2的弧度值进行随机旋转
tf.keras.layers.RandomBrightness(factor=0.5, value_range=(0.0, 1.0), seed=123), #按照0.1比例调整亮度
tf.keras.layers.RandomContrast(factor=0.1)
])
# 第一个层表示进行随机的水平和垂直翻转,而第二个层表示按照 0.2 的弧度值进行随机旋转。
#其余增强方式:https://www.tensorflow.org/api_docs/python/tf/keras/layers/RandomRotation
# Add the image to a batch.
image = tf.expand_dims(images[i], 0)
plt.figure(figsize=(8, 8))
for i in range(9):
augmented_image = data_augmentation(image)
ax = plt.subplot(3, 3, i + 1)
plt.imshow(augmented_image[0])
plt.axis("off")
三、增强方式
方法一:将其嵌入model中
model_base = tf.keras.Sequential([
data_augmentation,
layers.Conv2D(16, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
])
这样做的好处是:
- 数据增强这块的工作可以得到GPU的加速(如果你使用了GPU训练的话)
注意:只有在模型训练时(Model.fit)才会进行增强,在模型评估(Model.evaluate)以及预测(Model.predict)时并不会进行增强操作。
方法二:在Dataset数据集中进行数据增强
batch_size = 32
AUTOTUNE = tf.data.AUTOTUNE
#定义处理函数,只有training数据集会处理
def prepare(ds):
ds = ds.map(lambda x, y: (data_augmentation(x, training=True), y), num_parallel_calls=AUTOTUNE)
return ds
train_ds = prepare(train_ds)
四、训练模型
model = tf.keras.Sequential([
model_base,
layers.Conv2D(16, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(32, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(len(class_names))
])
在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:
- 损失函数(loss):用于衡量模型在训练期间的准确率。
- 优化器(optimizer):决定模型如何根据其看到的数据和自身的损失函数进行更新。
- 评价函数(metrics):用于监控训练和测试步骤。以下示例使用了准确率,即被正确分类的图像的比率。
model.compile(optimizer='adam',
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
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m2s[0m 116ms/step - accuracy: 0.5252 - loss: 0.6915 - val_accuracy: 0.4257 - val_loss: 0.7044
Epoch 2/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 30ms/step - accuracy: 0.5461 - loss: 0.6897 - val_accuracy: 0.5068 - val_loss: 0.6871
Epoch 3/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m1s[0m 35ms/step - accuracy: 0.6517 - loss: 0.6707 - val_accuracy: 0.7500 - val_loss: 0.6056
Epoch 4/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m1s[0m 45ms/step - accuracy: 0.6466 - loss: 0.6242 - val_accuracy: 0.7568 - val_loss: 0.5237
Epoch 5/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m1s[0m 41ms/step - accuracy: 0.6958 - loss: 0.5998 - val_accuracy: 0.7365 - val_loss: 0.6128
Epoch 6/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m1s[0m 37ms/step - accuracy: 0.7187 - loss: 0.6327 - val_accuracy: 0.7230 - val_loss: 0.5495
Epoch 7/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m1s[0m 37ms/step - accuracy: 0.7182 - loss: 0.5746 - val_accuracy: 0.7770 - val_loss: 0.5527
Epoch 8/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 34ms/step - accuracy: 0.7288 - loss: 0.5921 - val_accuracy: 0.8176 - val_loss: 0.4373
Epoch 9/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 31ms/step - accuracy: 0.7544 - loss: 0.4827 - val_accuracy: 0.8243 - val_loss: 0.3807
Epoch 10/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m1s[0m 29ms/step - accuracy: 0.7535 - loss: 0.5227 - val_accuracy: 0.8446 - val_loss: 0.4185
Epoch 11/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 29ms/step - accuracy: 0.7958 - loss: 0.4514 - val_accuracy: 0.8649 - val_loss: 0.3466
Epoch 12/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 29ms/step - accuracy: 0.8288 - loss: 0.3707 - val_accuracy: 0.8581 - val_loss: 0.3243
Epoch 13/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 29ms/step - accuracy: 0.8466 - loss: 0.3749 - val_accuracy: 0.7973 - val_loss: 0.4575
Epoch 14/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m1s[0m 29ms/step - accuracy: 0.8277 - loss: 0.4484 - val_accuracy: 0.8784 - val_loss: 0.3096
Epoch 15/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 29ms/step - accuracy: 0.8629 - loss: 0.2800 - val_accuracy: 0.8716 - val_loss: 0.2454
Epoch 16/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 29ms/step - accuracy: 0.8496 - loss: 0.3098 - val_accuracy: 0.9054 - val_loss: 0.1984
Epoch 17/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m1s[0m 29ms/step - accuracy: 0.8630 - loss: 0.2889 - val_accuracy: 0.9257 - val_loss: 0.2030
Epoch 18/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 29ms/step - accuracy: 0.8820 - loss: 0.2658 - val_accuracy: 0.9257 - val_loss: 0.2008
Epoch 19/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 29ms/step - accuracy: 0.8940 - loss: 0.2895 - val_accuracy: 0.9324 - val_loss: 0.1662
Epoch 20/20
[1m14/14[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m1s[0m 31ms/step - accuracy: 0.8923 - loss: 0.2681 - val_accuracy: 0.8919 - val_loss: 0.2506
loss, acc = model.evaluate(test_ds)
print("Accuracy", acc)
[1m1/1[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 409ms/step - accuracy: 0.8438 - loss: 0.2309
Accuracy 0.84375
五、自定义增强函数
import random
# 这是大家可以自由发挥的一个地方
def aug_img(image):
seed = (random.randint(0,9), 0)
# 随机改变图像对比度
stateless_random_brightness = tf.image.stateless_random_contrast(image, lower=0.1, upper=1.0, seed=seed)
return stateless_random_brightness
image = tf.expand_dims(images[3]*255, 0)
print("Min and max pixel values:", image.numpy().min(), image.numpy().max())
Min and max pixel values: 14.000048 253.28577
plt.figure(figsize=(8, 8))
for i in range(9):
augmented_image = aug_img(image)
ax = plt.subplot(3, 3, i + 1)
plt.imshow(augmented_image[0].numpy().astype("uint8"))
plt.axis("off")
参考上文的 preprocess_image
函数,将 aug_img
函数嵌入到 preprocess_image
函数中,在数据预处理时完成数据增强就OK啦。
六、总结
学习了不同的数据增强方法并且了解如何用增强方法预处理数据和引入模型训练