亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

一文詳解CNN 解決 Flowers 圖像分類任務(wù)

 更新時(shí)間:2023年03月10日 14:47:12   作者:我是王大你是誰(shuí)  
這篇文章主要為大家介紹了CNN 解決 Flowers 圖像分類任務(wù)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

前言

本文主要任務(wù)是使用通過(guò) tf.keras.Sequential 搭建的模型進(jìn)行各種花朵圖像的分類,主要涉及到的內(nèi)容有三個(gè)部分:

  • 使用 tf.keras.Sequential 搭建模型。
  • 使用 tf.keras.utils.image_dataset_from_directory 從磁盤中高效加載數(shù)據(jù)。
  • 使用了一定的防止過(guò)擬合的方法,如豐富訓(xùn)練樣本的數(shù)量、在數(shù)據(jù)處理過(guò)程中加入了數(shù)據(jù)增強(qiáng)、全連接層加入了 Dropout 等。

本文所用的環(huán)境為 tensorlfow-cpu= 2.4 ,python 版本為 3.8 。

主要章節(jié)介紹如下:

  • 加載并展示數(shù)據(jù)
  • 構(gòu)件處理圖像的 pipeline
  • 搭建深度學(xué)習(xí)分類模型
  • 訓(xùn)練模型并觀察結(jié)果
  • 加入了抑制過(guò)擬合措施并重新進(jìn)行模型的訓(xùn)練和測(cè)試

加載并展示數(shù)據(jù)

(1)該數(shù)據(jù)需要從網(wǎng)上下載,需要耐心等待片刻,下載下來(lái)自動(dòng)會(huì)存放在“你的主目錄.keras\datasets\flower_photos”。

(2)數(shù)據(jù)中總共有 5 種類,分別是 daisy、 dandelion、roses、sunflowers、tulips,總共包含了 3670 張圖片。

(3) 隨機(jī)展示了一張花朵的圖片。

import matplotlib.pyplot as plt
import numpy as np
import PIL
import tensorflow as tf
import pathlib
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
import random
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*.jpg')))
print("總共包含%d張圖片,下面隨便展示一張玫瑰的圖片樣例:"%image_count)
roses = list(data_dir.glob('roses/*'))
PIL.Image.open(str(random.choice(roses)))

結(jié)果打印:

總共包含3670張圖片,下面隨便展示一張玫瑰的圖片樣例:

構(gòu)件處理圖像的 pipeline

(1)使用 tf.keras.utils.image_dataset_from_directory 可以將我們的花朵圖片數(shù)據(jù),從磁盤加載到內(nèi)存中,并形成 tensorflow 高效的 tf.data.Dataset 類型。

(2)我們將數(shù)據(jù)集 shuffle 之后,進(jìn)行二八比例的隨機(jī)抽取分配,80% 的數(shù)據(jù)作為我們的訓(xùn)練集,共 2936 張圖片, 20% 的數(shù)據(jù)集作為我們的測(cè)試集,共 734 張圖片。

(3)我們使用 Dataset.cache 和 Dataset.prefetch 來(lái)提升數(shù)據(jù)的處理速度,使用 cache 在將數(shù)據(jù)從磁盤加載到 cache 之后,就可以將數(shù)據(jù)一直放 cache 中便于我們的后續(xù)訪問(wèn),這可以保證在訓(xùn)練過(guò)程中數(shù)據(jù)的處理不會(huì)成為計(jì)算的瓶頸。另外使用 prefetch 可以在 GPU 訓(xùn)練模型的時(shí)候,CPU 將之后需要的數(shù)據(jù)提前進(jìn)行處理放入 cache 中,也是為了提高數(shù)據(jù)的處理性能,加快整個(gè)訓(xùn)練過(guò)程,不至于訓(xùn)練模型時(shí)浪費(fèi)時(shí)間等待數(shù)據(jù)。

(4)我們隨便選取了 6 張圖像進(jìn)行展示,可以看到它們的圖片以及對(duì)應(yīng)的標(biāo)簽。

batch_size = 32
img_height = 180
img_width = 180
train_ds = tf.keras.utils.image_dataset_from_directory( data_dir, validation_split=0.2, subset="training", seed=1, image_size=(img_height, img_width), batch_size=batch_size)
val_ds = tf.keras.utils.image_dataset_from_directory( data_dir,  validation_split=0.2, subset="validation", seed=1, image_size=(img_height, img_width),batch_size=batch_size)
class_names = train_ds.class_names
num_classes = len(class_names)
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
plt.figure(figsize=(5, 5))
for images, labels in train_ds.take(1):
    for i in range(6):
        ax = plt.subplot(2, 3, i + 1)
        plt.imshow(images[i].numpy().astype("uint8"))
        plt.title(class_names[labels[i]])
        plt.axis("off")

結(jié)果打印:

Found 3670 files belonging to 5 classes.
Using 2936 files for training.
Found 3670 files belonging to 5 classes.
Using 734 files for validation.

搭建深度學(xué)習(xí)分類模型

(1)因?yàn)樽畛醯膱D片都是 RGB 三通道圖片,像素點(diǎn)的值在 [0,255] 之間,為了加速模型的收斂,我們要將所有的數(shù)據(jù)進(jìn)行歸一化操作。所以在模型的第一層加入了 layers.Rescaling 對(duì)圖片進(jìn)行處理。

(2)使用了三個(gè)卷積塊,每個(gè)卷積塊中包含了卷積層和池化層,并且每一個(gè)卷積層中都添加了 relu 激活函數(shù),卷積層不斷提取圖片的特征,池化層可以有效的所見(jiàn)特征矩陣的尺寸,同時(shí)也可以減少最后連接層的中的參數(shù)數(shù)量,權(quán)重參數(shù)少的同時(shí)也起到了加快計(jì)算速度和防止過(guò)擬合的作用。

(3)最后加入了兩層全連接層,輸出對(duì)圖片的分類預(yù)測(cè) logit 。

(4)使用 Adam 作為我們的模型優(yōu)化器,使用 SparseCategoricalCrossentropy 計(jì)算我們的損失值,在訓(xùn)練過(guò)程中觀察 accuracy 指標(biāo)。

model = Sequential([
  layers.Rescaling(1./255, input_shape=(img_height, img_width, 3)),
  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(num_classes)
])
model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])

訓(xùn)練模型并觀察結(jié)果

(1)我們使用訓(xùn)練集進(jìn)行模型的訓(xùn)練,使用驗(yàn)證集進(jìn)行模型的驗(yàn)證,總共訓(xùn)練 5 個(gè) epoch 。

(2)我們通過(guò)對(duì)訓(xùn)練過(guò)程中產(chǎn)生的準(zhǔn)確率和損失值,與驗(yàn)證過(guò)程中產(chǎn)生的準(zhǔn)確率和損失值進(jìn)行繪圖對(duì)比,訓(xùn)練時(shí)的準(zhǔn)確率高出驗(yàn)證時(shí)的準(zhǔn)確率很多,訓(xùn)練時(shí)的損失值遠(yuǎn)遠(yuǎn)低于驗(yàn)證時(shí)的損失值,這說(shuō)明模型存在過(guò)擬合風(fēng)險(xiǎn)。正常的情況這兩個(gè)指標(biāo)應(yīng)該是大體呈現(xiàn)同一個(gè)發(fā)展趨勢(shì)。

epochs = 5
history = model.fit(train_ds, validation_data=val_ds, epochs=epochs)
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

結(jié)果打印:

Epoch 1/5
92/92 [==============================] - 45s 494ms/step - loss: 0.2932 - accuracy: 0.8992 - val_loss: 1.2603 - val_accuracy: 0.6417
Epoch 2/5
92/92 [==============================] - 40s 436ms/step - loss: 0.1814 - accuracy: 0.9414 - val_loss: 1.5241 - val_accuracy: 0.6267
Epoch 3/5
92/92 [==============================] - 36s 394ms/step - loss: 0.0949 - accuracy: 0.9745 - val_loss: 1.6629 - val_accuracy: 0.6499
Epoch 4/5
92/92 [==============================] - 48s 518ms/step - loss: 0.0554 - accuracy: 0.9860 - val_loss: 1.7566 - val_accuracy: 0.6621
Epoch 5/5
92/92 [==============================] - 39s 419ms/step - loss: 0.0341 - accuracy: 0.9918 - val_loss: 2.1150 - val_accuracy: 0.6335

加入了抑制過(guò)擬合措施并重新進(jìn)行模型的訓(xùn)練和測(cè)試

(1)當(dāng)訓(xùn)練樣本數(shù)量較少時(shí),通常會(huì)發(fā)生過(guò)擬合現(xiàn)象。我們可以操作數(shù)據(jù)增強(qiáng)技術(shù),通過(guò)隨機(jī)翻轉(zhuǎn)、旋轉(zhuǎn)等方式來(lái)增加樣本的豐富程度。常見(jiàn)的數(shù)據(jù)增強(qiáng)處理方式有:tf.keras.layers.RandomFlip、tf.keras.layers.RandomRotation和 tf.keras.layers.RandomZoom。這些方法可以像其他層一樣包含在模型中,并在 GPU 上運(yùn)行。

(2)這里挑選了一張圖片,對(duì)其進(jìn)行 6 次執(zhí)行數(shù)據(jù)增強(qiáng),可以看到得到了經(jīng)過(guò)一定程度縮放、旋轉(zhuǎn)、反轉(zhuǎn)的數(shù)據(jù)集。

data_augmentation = keras.Sequential([
    layers.RandomFlip("horizontal", input_shape=(img_height, img_width, 3)),
    layers.RandomRotation(0.1),
    layers.RandomZoom(0.5)
])
plt.figure(figsize=(5, 5))
for images, _ in train_ds.take(1):
    for i in range(6):
        augmented_images = data_augmentation(images)
        ax = plt.subplot(2, 3, i + 1)
        plt.imshow(augmented_images[0].numpy().astype("uint8"))
        plt.axis("off")

(3)在模型架構(gòu)的開(kāi)始加入數(shù)據(jù)增強(qiáng)層,同時(shí)在全連接層的地方加入 Dropout ,進(jìn)行神經(jīng)元的隨機(jī)失活,這兩個(gè)方法的加入可以有效抑制模型過(guò)擬合的風(fēng)險(xiǎn)。其他的模型結(jié)構(gòu)、優(yōu)化器、損失函數(shù)、觀測(cè)值和之前相同。通過(guò)繪制數(shù)據(jù)圖我們發(fā)現(xiàn),使用這些措施很明顯減少了過(guò)擬合的風(fēng)險(xiǎn)。

model = Sequential([
  data_augmentation,
  layers.Rescaling(1./255),
  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.Dropout(0.2),
  layers.Flatten(),
  layers.Dense(128, activation='relu'),
  layers.Dense(num_classes, name="outputs")
])
model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
epochs = 15
history = model.fit( train_ds, validation_data=val_ds, epochs=epochs)
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

結(jié)果打?。?/p>

92/92 [==============================] - 57s 584ms/step - loss: 1.3080 - accuracy: 0.4373 - val_loss: 1.0929 - val_accuracy: 0.5749
Epoch 2/15
92/92 [==============================] - 41s 445ms/step - loss: 1.0763 - accuracy: 0.5596 - val_loss: 1.3068 - val_accuracy: 0.5204
...
Epoch 14/15
92/92 [==============================] - 59s 643ms/step - loss: 0.6306 - accuracy: 0.7585 - val_loss: 0.7963 - val_accuracy: 0.7044
Epoch 15/15
92/92 [==============================] - 42s 452ms/step - loss: 0.6155 - accuracy: 0.7691 - val_loss: 0.8513 - val_accuracy: 0.6975

(4)最后我們使用一張隨機(jī)下載的圖片,用模型進(jìn)行類別的預(yù)測(cè),發(fā)現(xiàn)可以識(shí)別出來(lái)。

sunflower_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/592px-Red_sunflower.jpg"
sunflower_path = tf.keras.utils.get_file('Red_sunflower', origin=sunflower_url)
img = tf.keras.utils.load_img(  sunflower_path, target_size=(img_height, img_width) )
img_array = tf.keras.utils.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) 
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
print(  "這張圖片最有可能屬于 {} ,有 {:.2f} 的置信度。".format(class_names[np.argmax(score)], 100 * np.max(score)))

結(jié)果打印:

這張圖片最有可能屬于 sunflowers ,有 97.39 的置信度。

以上就是一文詳解CNN 解決 Flowers 圖像分類任務(wù)的詳細(xì)內(nèi)容,更多關(guān)于CNN Flowers圖像分類的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python?Prometheus接口揭秘?cái)?shù)據(jù)科學(xué)新技巧

    Python?Prometheus接口揭秘?cái)?shù)據(jù)科學(xué)新技巧

    本篇文章將分享Prometheus?API的基本概念到PromQL查詢語(yǔ)言的應(yīng)用,再到如何通過(guò)Python與Prometheus?API進(jìn)行無(wú)縫交互,通過(guò)豐富的示例代碼和詳細(xì)的講解,將解鎖使用Python進(jìn)行實(shí)時(shí)監(jiān)控的奇妙世界,為讀者打開(kāi)更廣闊的數(shù)據(jù)分析視野
    2024-01-01
  • Python中Wxpython實(shí)現(xiàn)剪切、復(fù)制、粘貼和文件打開(kāi)示例

    Python中Wxpython實(shí)現(xiàn)剪切、復(fù)制、粘貼和文件打開(kāi)示例

    我們?cè)赑ython開(kāi)發(fā)中中,可以使用WxPython庫(kù)來(lái)創(chuàng)建GUI應(yīng)用程序,并實(shí)現(xiàn)剪切、復(fù)制、粘貼和文件打開(kāi)功能,本文就來(lái)介紹一下,感興趣的可以了解一下
    2024-03-03
  • 零基礎(chǔ)寫python爬蟲(chóng)之打包生成exe文件

    零基礎(chǔ)寫python爬蟲(chóng)之打包生成exe文件

    本文介紹了通過(guò)pyinstaller和pywin32兩個(gè)插件在windows環(huán)境下,將py文件打包成exe文件,有需要的朋友可以參考下
    2014-11-11
  • Numpy array數(shù)據(jù)的增、刪、改、查實(shí)例

    Numpy array數(shù)據(jù)的增、刪、改、查實(shí)例

    今天小編就為大家分享一篇Numpy array數(shù)據(jù)的增、刪、改、查實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-06-06
  • Django 緩存配置Redis使用詳解

    Django 緩存配置Redis使用詳解

    這篇文章主要介紹了Django 緩存配置Redis使用詳解,緩存是將一些常用的數(shù)據(jù)保存內(nèi)存或者memcache中,在一定的時(shí)間內(nèi)有用戶來(lái)訪問(wèn)這些數(shù)據(jù)時(shí),則不再去執(zhí)行數(shù)據(jù)庫(kù)及渲染等操作,而是直接從內(nèi)存或memcache的緩存中去取得數(shù)據(jù),然后返回給用戶
    2019-07-07
  • Python入門教程(三十六)Python的文件寫入

    Python入門教程(三十六)Python的文件寫入

    這篇文章主要介紹了Python入門教程(三十六)Python的文件寫入,open()函數(shù)可以打開(kāi)一個(gè)文件供讀取或?qū)懭?,如果這個(gè)函數(shù)執(zhí)行成功,會(huì)回傳文件對(duì)象,需要的朋友可以參考下
    2023-05-05
  • 對(duì)python中兩種列表元素去重函數(shù)性能的比較方法

    對(duì)python中兩種列表元素去重函數(shù)性能的比較方法

    今天小編就為大家分享一篇對(duì)python中兩種列表元素去重函數(shù)性能的比較方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-06-06
  • 基于Python實(shí)現(xiàn)Excel轉(zhuǎn)Markdown表格

    基于Python實(shí)現(xiàn)Excel轉(zhuǎn)Markdown表格

    Markdown(也簡(jiǎn)稱md)作為一種輕量級(jí)標(biāo)記語(yǔ)言,因其易寫易讀,效果美觀大方,不僅被眾多網(wǎng)站使用,也是程序員們做筆記、寫文檔的首選。本文將利用Python實(shí)現(xiàn)Excel轉(zhuǎn)Markdown表格,感興趣的可以了解一下
    2022-04-04
  • Python實(shí)現(xiàn)OpenCV的安裝與使用示例

    Python實(shí)現(xiàn)OpenCV的安裝與使用示例

    這篇文章主要介紹了Python實(shí)現(xiàn)OpenCV的安裝與使用,結(jié)合實(shí)例形式分析了Python中OpenCV的安裝及針對(duì)圖片的相關(guān)操作技巧,需要的朋友可以參考下
    2018-03-03
  • Python簡(jiǎn)單實(shí)現(xiàn)enum功能的方法

    Python簡(jiǎn)單實(shí)現(xiàn)enum功能的方法

    這篇文章主要介紹了Python簡(jiǎn)單實(shí)現(xiàn)enum功能的方法,簡(jiǎn)單分析了Python實(shí)現(xiàn)enum功能的相關(guān)技巧,需要的朋友可以參考下
    2016-04-04

最新評(píng)論