自学内容网 自学内容网

深度学习笔记20_数据增强

一、我的环境

1.语言环境:Python 3.9

2.编译器:Pycharm

3.深度学习环境:TensorFlow 2.10.0

二、GPU设置

       若使用的是cpu则可忽略

import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")

if gpus:
    gpu0 = gpus[0] #如果有多个GPU,仅使用第0个GPU
    tf.config.experimental.set_memory_growth(gpu0, True) #设置GPU显存用量按需使用
    tf.config.set_visible_devices([gpu0],"GPU")

、加载数据

data_dir   = "./data/"
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)

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)

       由于原始数据集不包含测试集,因此需要创建一个。使用 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))
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(5, 8, i + 1) 
        plt.imshow(images[i])
        plt.title(class_names[labels[i]])
        
        plt.axis("off")

 

、数据增强

我们可以使用 tf.keras.layers.experimental.preprocessing.RandomFliptf.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.experimental.preprocessing.RandomFlip("horizontal_and_vertical"),
  tf.keras.layers.experimental.preprocessing.RandomRotation(0.2),
])

第一个层表示进行随机的水平和垂直翻转,而第二个层表示按照 0.2 的弧度值进行随机旋转。 

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 = 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

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([
  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))
])
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
14/14 [==============================] - 9s 60ms/step - loss: 0.8157 - accuracy: 0.5452 - val_loss: 0.6570 - val_accuracy: 0.5811
Epoch 2/20
14/14 [==============================] - 0s 32ms/step - loss: 0.5555 - accuracy: 0.7310 - val_loss: 0.4195 - val_accuracy: 0.8311
Epoch 3/20
14/14 [==============================] - 0s 30ms/step - loss: 0.2668 - accuracy: 0.8881 - val_loss: 0.4676 - val_accuracy: 0.8041
Epoch 4/20
14/14 [==============================] - 0s 31ms/step - loss: 0.1672 - accuracy: 0.9310 - val_loss: 0.3413 - val_accuracy: 0.8649
Epoch 5/20
14/14 [==============================] - 0s 30ms/step - loss: 0.1526 - accuracy: 0.9452 - val_loss: 0.2555 - val_accuracy: 0.9054
Epoch 6/20
14/14 [==============================] - 0s 29ms/step - loss: 0.0710 - accuracy: 0.9881 - val_loss: 0.2825 - val_accuracy: 0.9122
Epoch 7/20
14/14 [==============================] - 0s 29ms/step - loss: 0.0278 - accuracy: 0.9976 - val_loss: 0.2849 - val_accuracy: 0.9054
Epoch 8/20
14/14 [==============================] - 0s 28ms/step - loss: 0.0140 - accuracy: 0.9976 - val_loss: 0.2841 - val_accuracy: 0.9122
Epoch 9/20
14/14 [==============================] - 0s 29ms/step - loss: 0.0103 - accuracy: 1.0000 - val_loss: 0.3034 - val_accuracy: 0.9122
Epoch 10/20
14/14 [==============================] - 0s 29ms/step - loss: 0.0060 - accuracy: 1.0000 - val_loss: 0.7403 - val_accuracy: 0.8446
Epoch 11/20
14/14 [==============================] - 0s 29ms/step - loss: 0.0620 - accuracy: 0.9738 - val_loss: 0.2892 - val_accuracy: 0.9054
Epoch 12/20
14/14 [==============================] - 0s 29ms/step - loss: 0.0377 - accuracy: 0.9881 - val_loss: 0.3887 - val_accuracy: 0.8919
Epoch 13/20
14/14 [==============================] - 0s 29ms/step - loss: 0.0312 - accuracy: 0.9881 - val_loss: 0.5183 - val_accuracy: 0.8784
Epoch 14/20
14/14 [==============================] - 0s 28ms/step - loss: 0.0264 - accuracy: 0.9929 - val_loss: 0.7976 - val_accuracy: 0.8784
Epoch 15/20
14/14 [==============================] - 0s 28ms/step - loss: 0.0697 - accuracy: 0.9690 - val_loss: 0.3325 - val_accuracy: 0.8851
Epoch 16/20
14/14 [==============================] - 0s 28ms/step - loss: 0.0270 - accuracy: 0.9952 - val_loss: 0.4877 - val_accuracy: 0.9122
Epoch 17/20
14/14 [==============================] - 0s 29ms/step - loss: 0.0129 - accuracy: 0.9952 - val_loss: 1.3700 - val_accuracy: 0.8378
Epoch 18/20
14/14 [==============================] - 0s 28ms/step - loss: 0.0229 - accuracy: 0.9905 - val_loss: 0.4864 - val_accuracy: 0.9122
Epoch 19/20
14/14 [==============================] - 0s 28ms/step - loss: 0.0231 - accuracy: 0.9952 - val_loss: 0.3220 - val_accuracy: 0.9257
Epoch 20/20
14/14 [==============================] - 0s 28ms/step - loss: 0.0331 - accuracy: 0.9881 - val_loss: 0.4932 - val_accuracy: 0.8919

七、自定义增强函数

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

八、总结

数据增强类型:

1.图像增强

  • 随机旋转
  • 随机翻转
  • 随机缩放
  • 裁剪和调整大小

2.文本数据增强

字符级别在字符级别,数据增强涉及更改文本数据中的单个字符。

短语级别在短语级别扩充数据涉及以连贯的方式修改短语或单词组。

3.音频数据增强

噪声注入:我们可以通过简单地使用 numpy 向数据添加一些随机值来增加音频样本的数量。

转移时间:转移时间的想法非常简单。它只是随机将音频向左/向右移动。

改变音高:我们可以使用 librosa 函数改变音高。

改变速度:我们可以使用 librosa 函数以固定速率拉伸音频时间序列。


原文地址:https://blog.csdn.net/L1073203482/article/details/143025700

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!