偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

使用TensorFlow和Keras創(chuàng)建貓狗圖片深度學習分類器

人工智能 深度學習
本文將帶你了解如何使用使用TensorFlow和Keras創(chuàng)建貓狗圖片深度學習分類器。

圖片

在本文中,我們將使用TensorFlow和Keras創(chuàng)建一個圖像分類器,可以區(qū)分貓和狗的圖像。為了做到這一點,我們將使用TensorFlow數(shù)據(jù)集中的cats_vs_dogs數(shù)據(jù)集。該數(shù)據(jù)集由25000張打過標簽的貓和狗的圖像組成,其中80%的圖像用于訓練,10%用于驗證,10%用于測試。

加載數(shù)據(jù)

我們從使用TensorFlow Datasets加載數(shù)據(jù)集開始。將數(shù)據(jù)集拆分為訓練集、驗證集和測試集,分別占數(shù)據(jù)的80%、10%和10%,并定義一個函數(shù)來顯示數(shù)據(jù)集中的一些樣本圖像。

import tensorflow as tf
import matplotlib.pyplot as plt
import tensorflow_datasets as tfds

# 加載數(shù)據(jù)
(train_data, validation_data, test_data), info = tfds.load('cats_vs_dogs',
                                                           split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],
                                                           with_info=True,
                                                           as_supervised=True)
# 獲取圖像的標簽
label_names = info.features['label'].names
# 定義一個函數(shù)來顯示一些樣本圖像
plt.figure(figsize=(10, 10))
for i, (image, label) in enumerate(train_data.take(9)):
    ax = plt.subplot(3, 3, i + 1)
    plt.imshow(image)
    plt.title(label_names[label])
    plt.axis('off')

圖片

預處理數(shù)據(jù)

在訓練模型之前,需要對數(shù)據(jù)進行預處理。將把圖片的大小調(diào)整為150x150像素的統(tǒng)一尺寸,將像素值歸一化為0和1之間,并對數(shù)據(jù)進行批處理,這樣就可以將其分批導入模型中。

IMG_SIZE = 150
def format_image(image, label):
    image = tf.cast(image, tf.float32) / 255.0  # Normalize the pixel values
    image = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))  # Resize to the desired size
    return image, label
batch_size = 32
train_data = train_data.map(format_image).shuffle(1000).batch(batch_size)
validation_data = validation_data.map(format_image).batch(batch_size)
test_data = test_data.map(format_image).batch(batch_size)

圖片

搭建模型

本文將使用預先訓練好的MobileNet V2模型作為基礎模型,并在其中添加一個全局平均池化層和一個緊密層來進行分類。本文將凍結(jié)基礎模型的權(quán)重,以便在訓練期間只更新頂層的權(quán)重。

base_model = tf.keras.applications.MobileNetV2(input_shape=(IMG_SIZE, IMG_SIZE, 3),
                                               include_top=False,
                                               weights='imagenet')
base_model.trainable = False
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
prediction_layer = tf.keras.layers.Dense(1)
model = tf.keras.Sequential([
    base_model,
    global_average_layer,
    prediction_layer
])
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.0001),
              loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              metrics=['accuracy'])

訓練模型

本文將對模型進行3個周期的訓練,并在每個周期之后在驗證集上對其進行驗證。我們將在訓練后保存模型,這樣就可以在以后的測試中使用它。

global_average_layer = tf.keras.layers.GlobalAveragePooling2D()
prediction_layer = tf.keras.layers.Dense(1)
model = tf.keras.Sequential([
    base_model,
    global_average_layer,
    prediction_layer
])
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.0001),
              loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
              metrics=['accuracy'])
history = model.fit(train_data,
                    epochs=3,
                    validation_data=validation_data)

圖片

模型歷史

如果想知道Mobilenet V2層是如何工作的,如下圖所示是該層的一個結(jié)果。

圖片

評估模型

訓練完成后將在測試集上評估該模型,看看它在新數(shù)據(jù)上的表現(xiàn)如何。

loaded_model = tf.keras.models.load_model('cats_vs_dogs.h5')
test_loss, test_accuracy = loaded_model.evaluate(test_data)
print('Test accuracy:', test_accuracy)

進行預測

最后,本文將使用該模型對測試集中的一些樣本圖像進行預測,并顯示結(jié)果。

for image , _ in test_.take(90) : 
    pass

pre = loaded_model.predict(image)

plt.figure(figsize = (10 , 10))
j = None
for value in enumerate(pre) : 
    plt.subplot(7,7,value[0]+1)
    plt.imshow(image[value[0]])
    plt.xticks([])
    plt.yticks([])
    if value[1] > pre.mean() :
        j = 1
        color = 'blue' if j == _[value[0]] else 'red'
        plt.title('dog' , color = color)
    else : 
        j = 0
        color = 'blue' if j == _[value[0]] else 'red'
        plt.title('cat' , color = color)

plt.show()

圖片

大功告成!我們通過使用TensorFlow和Keras創(chuàng)建了一個圖像分類器,可以區(qū)分貓和狗的圖像。通過一些調(diào)整和微調(diào),也可以將這種方法應用于其他圖像分類問題。

責任編輯:武曉燕 來源: Python學研大本營
相關推薦

2022-06-29 09:00:00

前端圖像分類模型SQL

2017-07-24 13:37:42

深度學習KerasTensorFlow

2018-04-09 10:20:32

深度學習

2018-10-15 10:08:53

程序員技能深度學習

2016-12-06 08:51:48

深度學習TensorFlow機器學習

2017-12-01 15:24:04

TensorFlow深度學習教程

2017-08-10 15:31:57

Apache Spar TensorFlow

2017-06-06 10:14:55

KerasTensorFlow深度學習

2022-08-15 15:16:20

機器學習圖片深度學習

2020-03-04 10:51:35

Python算法腳本語言

2021-02-03 13:56:09

KerasAPI深度學習

2016-12-27 15:33:25

softmax分類器課程

2018-01-15 09:49:25

Python精準分類

2017-10-30 13:34:22

深度學習KerasAPI

2024-09-11 08:34:28

2017-08-04 14:23:04

機器學習神經(jīng)網(wǎng)絡TensorFlow

2018-07-03 15:59:14

KerasPyTorch深度學習

2017-08-16 10:57:52

深度學習TensorFlowNLP

2021-11-02 11:48:39

深度學習惡意軟件觀察

2023-11-02 18:05:55

Ray深度學習
點贊
收藏

51CTO技術(shù)棧公眾號