數據增強,擴充數據集


1.概述

數據增強,可以幫助擴展數據集,對圖像的增強,就是對圖像的簡單形變,用來應對因拍照角度不同引起的圖片變形。

TensorFlow2給出了數據增強函數

2.數據增強(增大數據量)

 

 數據增強在小數據量上可以增加模型的泛化性,在實際應用模型是能體現出效果

 

 tf.keras.layers.Flatten()拉直層

拉直層可以變化張量的尺寸,把輸入特征拉直為一維數組,是不含計算參數的層

注: 1、 model.fit(x_train,y_train,batch_size=32,……)變為model.fit(image_gen_train.flow(x_train, y_train,batch_size=32), ……);

        2、數據增強函數的輸入要求是 4 維,通過 reshape 調整; 3、如果報錯:缺少scipy 庫, pip install scipy 即可。 

 

代碼:

沒有經過數據增強操作

import tensorflow as tf

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1)
model.summary()

  

加了數據增強
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)  # 給數據增加一個維度,從(60000, 28, 28)reshape為(60000, 28, 28, 1)

image_gen_train = ImageDataGenerator(
    rescale=1. / 1.,  # 如為圖像,分母為255時,可歸至0~1
    rotation_range=45,  # 隨機45度旋轉
    width_shift_range=.15,  # 寬度偏移
    height_shift_range=.15,  # 高度偏移
    horizontal_flip=False,  # 水平翻轉
    zoom_range=0.5  # 將圖像隨機縮放閾量50%
)
image_gen_train.fit(x_train)

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

model.fit(image_gen_train.flow(x_train, y_train, batch_size=32), epochs=5, validation_data=(x_test, y_test),
          validation_freq=1)
model.summary()

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM