TensorFlow實現(xiàn)數(shù)據(jù)增強的示例代碼
電腦環(huán)境:
語言環(huán)境:Python 3.8.0
編譯器:Jupyter Notebook
深度學習環(huán)境:tensorflow 2.17.0
一、前期工作
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") # 打印顯卡信息,確認GPU可用 print(gpus)
2、加載數(shù)據(jù)
data_dir = "./365-8-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)
Found 3400 files belonging to 2 classes.
Using 2380 files for training.
val_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 3400 files belonging to 2 classes.
Using 1020 files for validation.
由于原始數(shù)據(jù)集不包含測試集,因此需要創(chuàng)建一個。使用 tf.data.experimental.cardinality 確定驗證集中有多少批次的數(shù)據(jù),然后將其中的 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: 26
Number of test batches: 6
tf.data.experimental.cardinality
函數(shù)是一個用于確定tf.data.Dataset
對象中包含的元素數(shù)量的實驗性功能。然而,需要注意的是,這個函數(shù)并不總是能夠返回確切的元素數(shù)量,特別是對于無限數(shù)據(jù)集或包含復雜轉換的數(shù)據(jù)集。
數(shù)據(jù)一共有貓、狗兩類:
class_names = train_ds.class_names print(class_names)
[‘cat’, ‘dog’]
數(shù)據(jù)歸一化:
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)
數(shù)據(jù)可視化:
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")
二、數(shù)據(jù)增強
我們可以使用 tf.keras.layers.experimental.preprocessing.RandomFlip
與tf.keras.layers.experimental.preprocessing.RandomRotation
進行數(shù)據(jù)增強,當然還有其他的增強函數(shù)(新版本的tf增強函數(shù)調用函數(shù)不同):
- tf.keras.layers.experimental.preprocessing.RandomFlip:水平和垂直隨機翻轉每個圖像。
- tf.keras.layers.experimental.preprocessing.RandomRotation:隨機旋轉每個圖像。
- tf.keras.layers.experimental.preprocessing.RandomZoom:隨機裁剪和重新調整大小來模擬縮放效果。
- tf.keras.layers.experimental.preprocessing.RandomContrast:調整圖像的對比度。
- tf.keras.layers.experimental.preprocessing.RandomBrightness:調整圖像的亮度。
data_augmentation = tf.keras.Sequential([ tf.keras.layers.experimental.preprocessing.RandomFlip("horizontal_and_vertical"), tf.keras.layers.experimental.preprocessing.RandomRotation(0.2), ])
第一個層表示進行隨機的水平和垂直翻轉,而第二個層表示按照 0.2 的弧度值進行隨機旋轉。
增加一張圖片為一個批次:
# 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")
更多的數(shù)據(jù)增強方式可以參考:鏈接: link
三、增強方式
方法一:將其嵌入model中
model = tf.keras.Sequential([ data_augmentation, layers.Conv2D(16, 3, padding='same', activation='relu'), layers.MaxPooling2D(), ])
這樣做的好處是:
- 數(shù)據(jù)增強這塊的工作可以得到GPU的加速(如果你使用了GPU訓練的話)
注意:只有在模型訓練時(Model.fit)才會進行增強,在模型評估(Model.evaluate)以及預測(Model.predict)時并不會進行增強操作。
方法二:在Dataset數(shù)據(jù)集中進行數(shù)據(jù)增強
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
75/75 ━━━━━━━━━━━━━━━━━━━━ 399s 5s/step - accuracy: 0.5225 - loss: 293.7218 - val_accuracy: 0.6775 - val_loss: 0.5858
Epoch 2/20
75/75 ━━━━━━━━━━━━━━━━━━━━ 73s 376ms/step - accuracy: 0.7183 - loss: 0.5656 - val_accuracy: 0.8080 - val_loss: 0.4210
..............
Epoch 20/20
75/75 ━━━━━━━━━━━━━━━━━━━━ 25s 329ms/step - accuracy: 0.9430 - loss: 0.1563 - val_accuracy: 0.9263 - val_loss: 0.2544
loss, acc = model.evaluate(test_ds) print("Accuracy", acc)
6/6 ━━━━━━━━━━━━━━━━━━━━ 1s 100ms/step - accuracy: 0.9310 - loss: 0.1482
Accuracy 0.921875
五、自定義增強函數(shù)
import random # 這是大家可以自由發(fā)揮的一個地方 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: 2.4591687 241.47968
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")
將自定義增強函數(shù)應用到我們數(shù)據(jù)上
AUTOTUNE = tf.data.AUTOTUNE import random # 這是大家可以自由發(fā)揮的一個地方 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 def preprocess_image(image, label): image = image / 255.0 image = aug_img(image) return (image, label) # 歸一化處理 train_ds = train_ds.map(preprocess_image, num_parallel_calls=AUTOTUNE) train_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE)
六、總結
本次學習了使用兩種方式的數(shù)據(jù)增強提高模型性能以及自定義數(shù)據(jù)增強函數(shù)。
到此這篇關于TensorFlow實現(xiàn)數(shù)據(jù)增強的示例代碼的文章就介紹到這了,更多相關TensorFlow 數(shù)據(jù)增強內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
多線程爬蟲批量下載pcgame圖片url 保存為xml的實現(xiàn)代碼
用Python寫的多線程爬蟲批量下載pcgame的圖片url并保存為xml格式,主要是邏輯代碼,喜歡的朋友可以測試下2013-01-01pytorch從csv加載自定義數(shù)據(jù)模板的操作
這篇文章主要介紹了pytorch從csv加載自定義數(shù)據(jù)模板的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03Python CSS選擇器爬取京東網(wǎng)商品信息過程解析
這篇文章主要介紹了Python CSS選擇器爬取京東網(wǎng)商品信息過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06使用PyCharm在Github上保存代碼并在服務器上運行方式
這篇文章主要介紹了使用PyCharm在Github上保存代碼并在服務器上運行方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02Python實現(xiàn)連接MySQL數(shù)據(jù)庫的常見方法總結
這篇文章主要為大家介紹了兩種Python中用來連接 MySQL 數(shù)據(jù)庫的方法,并且針對這兩種方法,我們還將對代碼進行封裝和優(yōu)化,提高程序的可讀性和健壯性,需要的可以收藏一下2023-05-05