最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

TensorFlow實(shí)現(xiàn)數(shù)據(jù)增強(qiáng)的示例代碼

 更新時(shí)間:2024年08月27日 10:09:15   作者:oufoc  
?TensorFlow數(shù)據(jù)增強(qiáng)?是一種通過變換和擴(kuò)充訓(xùn)練數(shù)據(jù)的方法,本文主要介紹了TensorFlow實(shí)現(xiàn)數(shù)據(jù)增強(qiáng)的示例代碼,具有一定的參考價(jià)值,感興趣的可以了解游戲

電腦環(huán)境:
語言環(huán)境:Python 3.8.0
編譯器:Jupyter Notebook
深度學(xué)習(xí)環(huán)境:tensorflow 2.17.0

一、前期工作

1.設(shè)置GPU(如果使用的是CPU可以忽略這步)

import tensorflow as tf

gpus = tf.config.list_physical_devices("GPU")

if gpus:
    tf.config.experimental.set_memory_growth(gpus[0], True)  #設(shè)置GPU顯存用量按需使用
    tf.config.set_visible_devices([gpus[0]],"GPU")

# 打印顯卡信息,確認(rèn)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ù)集不包含測(cè)試集,因此需要?jiǎng)?chuàng)建一個(gè)。使用 tf.data.experimental.cardinality 確定驗(yàn)證集中有多少批次的數(shù)據(jù),然后將其中的 20% 移至測(cè)試集。

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ù)是一個(gè)用于確定tf.data.Dataset對(duì)象中包含的元素?cái)?shù)量的實(shí)驗(yàn)性功能。然而,需要注意的是,這個(gè)函數(shù)并不總是能夠返回確切的元素?cái)?shù)量,特別是對(duì)于無限數(shù)據(jù)集或包含復(fù)雜轉(zhuǎn)換的數(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ù)增強(qiáng)

我們可以使用 tf.keras.layers.experimental.preprocessing.RandomFlip tf.keras.layers.experimental.preprocessing.RandomRotation 進(jìn)行數(shù)據(jù)增強(qiáng),當(dāng)然還有其他的增強(qiáng)函數(shù)(新版本的tf增強(qiáng)函數(shù)調(diào)用函數(shù)不同):

  • tf.keras.layers.experimental.preprocessing.RandomFlip:水平和垂直隨機(jī)翻轉(zhuǎn)每個(gè)圖像。
  • tf.keras.layers.experimental.preprocessing.RandomRotation:隨機(jī)旋轉(zhuǎn)每個(gè)圖像。
  • tf.keras.layers.experimental.preprocessing.RandomZoom:隨機(jī)裁剪和重新調(diào)整大小來模擬縮放效果。
  • tf.keras.layers.experimental.preprocessing.RandomContrast:調(diào)整圖像的對(duì)比度。
  • tf.keras.layers.experimental.preprocessing.RandomBrightness:調(diào)整圖像的亮度。
data_augmentation = tf.keras.Sequential([
  tf.keras.layers.experimental.preprocessing.RandomFlip("horizontal_and_vertical"),
  tf.keras.layers.experimental.preprocessing.RandomRotation(0.2),
])

第一個(gè)層表示進(jìn)行隨機(jī)的水平和垂直翻轉(zhuǎn),而第二個(gè)層表示按照 0.2 的弧度值進(jìn)行隨機(jī)旋轉(zhuǎn)。
增加一張圖片為一個(gè)批次:

# 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ù)增強(qiáng)方式可以參考:鏈接: link

三、增強(qiáng)方式

方法一:將其嵌入model中

model = tf.keras.Sequential([
  data_augmentation,
  layers.Conv2D(16, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
])

這樣做的好處是:

  • 數(shù)據(jù)增強(qiáng)這塊的工作可以得到GPU的加速(如果你使用了GPU訓(xùn)練的話)
    注意:只有在模型訓(xùn)練時(shí)(Model.fit)才會(huì)進(jìn)行增強(qiáng),在模型評(píng)估(Model.evaluate)以及預(yù)測(cè)(Model.predict)時(shí)并不會(huì)進(jìn)行增強(qiáng)操作。

方法二:在Dataset數(shù)據(jù)集中進(jìn)行數(shù)據(jù)增強(qiáng)

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)

四、訓(xùn)練模型

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

五、自定義增強(qiáng)函數(shù)

import random
# 這是大家可以自由發(fā)揮的一個(gè)地方
def aug_img(image):
    seed = (random.randint(0,9), 0)
    # 隨機(jī)改變圖像對(duì)比度
    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")

在這里插入圖片描述

將自定義增強(qiáng)函數(shù)應(yīng)用到我們數(shù)據(jù)上

AUTOTUNE = tf.data.AUTOTUNE

import random
# 這是大家可以自由發(fā)揮的一個(gè)地方
def aug_img(image):
    seed = (random.randint(0,9), 0)
    # 隨機(jī)改變圖像對(duì)比度
    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)

六、總結(jié)

本次學(xué)習(xí)了使用兩種方式的數(shù)據(jù)增強(qiáng)提高模型性能以及自定義數(shù)據(jù)增強(qiáng)函數(shù)。

到此這篇關(guān)于TensorFlow實(shí)現(xiàn)數(shù)據(jù)增強(qiáng)的示例代碼的文章就介紹到這了,更多相關(guān)TensorFlow 數(shù)據(jù)增強(qiáng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python3.X 抓取火車票信息【修正版】

    python3.X 抓取火車票信息【修正版】

    這篇文章主要介紹了python3.X 抓取火車票信息修正版,本文是在源代碼的基礎(chǔ)上進(jìn)行的修改,需要的朋友可以參考下
    2018-06-06
  • 深入理解Django-Signals信號(hào)量

    深入理解Django-Signals信號(hào)量

    這篇文章主要介紹了深入理解Django-Signals信號(hào)量,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-02-02
  • python采集百度百科的方法

    python采集百度百科的方法

    這篇文章主要介紹了python采集百度百科的方法,涉及Python正則匹配及頁面抓取的相關(guān)技巧,需要的朋友可以參考下
    2015-06-06
  • Python接口自動(dòng)化淺析requests請(qǐng)求封裝原理

    Python接口自動(dòng)化淺析requests請(qǐng)求封裝原理

    本文主要通過源碼分析,總結(jié)出一套簡(jiǎn)潔的requests請(qǐng)求類封裝,幫助大家更好的由淺入深的理解python接口自動(dòng)化,希望對(duì)大家的python接口自動(dòng)化學(xué)習(xí)有所幫助
    2021-08-08
  • python中Event實(shí)現(xiàn)線程間同步介紹

    python中Event實(shí)現(xiàn)線程間同步介紹

    這篇文章主要介紹了python中Event實(shí)現(xiàn)線程間同步,Event是python線程間同步一種常用的方法,下列內(nèi)容總結(jié)需要的朋友可以參考一下
    2022-04-04
  • python中DDT數(shù)據(jù)驅(qū)動(dòng)的實(shí)現(xiàn)

    python中DDT數(shù)據(jù)驅(qū)動(dòng)的實(shí)現(xiàn)

    DDT是一種軟件測(cè)試方法,本文主要介紹了python中DDT數(shù)據(jù)驅(qū)動(dòng)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-04-04
  • Python實(shí)現(xiàn)將Word表格嵌入到Excel中

    Python實(shí)現(xiàn)將Word表格嵌入到Excel中

    把Word中的表格轉(zhuǎn)到Excel中,順便做一個(gè)調(diào)整。這個(gè)需求在實(shí)際工作中,很多人還是經(jīng)常碰到的!本文就將介紹如何利用Python實(shí)現(xiàn)這一功能,需要的朋友可以了解一下
    2021-12-12
  • Python安裝Gradio和常見安裝問題解決辦法

    Python安裝Gradio和常見安裝問題解決辦法

    Gradio是一款便捷的Python庫,專門用于創(chuàng)建機(jī)器學(xué)習(xí)模型的Web應(yīng)用,安裝通常簡(jiǎn)單,但偶爾會(huì)遇到依賴問題或環(huán)境配置錯(cuò)誤,這篇文章主要介紹了Python安裝Gradio和常見安裝問題解決辦法,需要的朋友可以參考下
    2024-10-10
  • pytorch學(xué)習(xí)教程之自定義數(shù)據(jù)集

    pytorch學(xué)習(xí)教程之自定義數(shù)據(jù)集

    這篇文章主要給大家介紹了關(guān)于pytorch學(xué)習(xí)教程之自定義數(shù)據(jù)集的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • pytorch?rpc實(shí)現(xiàn)分物理機(jī)器實(shí)現(xiàn)model?parallel的過程詳解

    pytorch?rpc實(shí)現(xiàn)分物理機(jī)器實(shí)現(xiàn)model?parallel的過程詳解

    這篇文章主要介紹了pytorch?rpc實(shí)現(xiàn)分物理機(jī)器實(shí)現(xiàn)model?parallel的過程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-05-05

最新評(píng)論

荆州市| 甘谷县| 安化县| 阳朔县| 皮山县| 高台县| 通州区| 吉首市| 开原市| 张家川| 巩留县| 金华市| 蒲城县| 宜兴市| 阿拉尔市| 自贡市| 滦平县| 尖扎县| 滕州市| 江华| 黑水县| 浦县| 宁夏| 剑阁县| 永德县| 雅江县| 舟山市| 东乡县| 荔浦县| 垫江县| 平陆县| 乌审旗| 买车| 大连市| 邯郸市| 藁城市| 惠水县| 新河县| 长治县| 璧山县| 和政县|