欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

一文詳解CNN 解決 Flowers 圖像分類任務

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

前言

本文主要任務是使用通過 tf.keras.Sequential 搭建的模型進行各種花朵圖像的分類,主要涉及到的內容有三個部分:

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

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

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

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

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

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

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

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

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

結果打?。?/p>

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

構件處理圖像的 pipeline

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

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

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

(4)我們隨便選取了 6 張圖像進行展示,可以看到它們的圖片以及對應的標簽。

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

結果打?。?/p>

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

搭建深度學習分類模型

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

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

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

(4)使用 Adam 作為我們的模型優(yōu)化器,使用 SparseCategoricalCrossentropy 計算我們的損失值,在訓練過程中觀察 accuracy 指標。

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'])

訓練模型并觀察結果

(1)我們使用訓練集進行模型的訓練,使用驗證集進行模型的驗證,總共訓練 5 個 epoch 。

(2)我們通過對訓練過程中產生的準確率和損失值,與驗證過程中產生的準確率和損失值進行繪圖對比,訓練時的準確率高出驗證時的準確率很多,訓練時的損失值遠遠低于驗證時的損失值,這說明模型存在過擬合風險。正常的情況這兩個指標應該是大體呈現(xiàn)同一個發(fā)展趨勢。

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

結果打?。?/p>

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

加入了抑制過擬合措施并重新進行模型的訓練和測試

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

(2)這里挑選了一張圖片,對其進行 6 次執(zhí)行數(shù)據(jù)增強,可以看到得到了經過一定程度縮放、旋轉、反轉的數(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)在模型架構的開始加入數(shù)據(jù)增強層,同時在全連接層的地方加入 Dropout ,進行神經元的隨機失活,這兩個方法的加入可以有效抑制模型過擬合的風險。其他的模型結構、優(yōu)化器、損失函數(shù)、觀測值和之前相同。通過繪制數(shù)據(jù)圖我們發(fā)現(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()

結果打?。?/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)最后我們使用一張隨機下載的圖片,用模型進行類別的預測,發(fā)現(xiàn)可以識別出來。

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

結果打?。?/p>

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

以上就是一文詳解CNN 解決 Flowers 圖像分類任務的詳細內容,更多關于CNN Flowers圖像分類的資料請關注腳本之家其它相關文章!

相關文章

  • Python?Prometheus接口揭秘數(shù)據(jù)科學新技巧

    Python?Prometheus接口揭秘數(shù)據(jù)科學新技巧

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

    Python中Wxpython實現(xiàn)剪切、復制、粘貼和文件打開示例

    我們在Python開發(fā)中中,可以使用WxPython庫來創(chuàng)建GUI應用程序,并實現(xiàn)剪切、復制、粘貼和文件打開功能,本文就來介紹一下,感興趣的可以了解一下
    2024-03-03
  • 零基礎寫python爬蟲之打包生成exe文件

    零基礎寫python爬蟲之打包生成exe文件

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

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

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

    Django 緩存配置Redis使用詳解

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

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

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

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

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

    基于Python實現(xiàn)Excel轉Markdown表格

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

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

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

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

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

最新評論