使用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 = 150def 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 = Falseglobal_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),也可以將這種方法應用于其他圖像分類問題。




























