實驗12-使用keras預訓練模型完成貓狗識別

阿飞藏泪發表於2024-04-27

版本python3.7 tensorflow版本為tensorflow-gpu版本2.6

執行結果:

這裡我用Gpu進行加速,訓練一回9秒,如果不啟用gpu,訓練一回會很慢。

程式碼:

#-*- codeing = utf-8 -*-
#@Time : 2022/10/2 11:44
#@Author : 程浩
#@File : 貓狗識別.py
#@Software: PyCharm
import tensorflow as tf
import keras
from keras import layers
import numpy as np
import os
import shutil
from tensorflow.keras.applications import VGG16
from tensorflow.keras.optimizers import Adam



#%%

base_dir = './dc'
train_dir = base_dir + '/train'
train_dog_dir = train_dir + '/dog'
train_cat_dir = train_dir + '/cat'
test_dir = base_dir + '/test'
test_dog_dir = test_dir + '/dog'
test_cat_dir = test_dir + '/cat'
dc_dir = '.=/dc/train'

#%%

if not os.path.exists(base_dir):

    os.mkdir(base_dir)

    os.mkdir(train_dir)
    os.mkdir(train_dog_dir)
    os.mkdir(train_cat_dir)
    os.mkdir(test_dir)
    os.mkdir(test_dog_dir)
    os.mkdir(test_cat_dir)

    fnames = ['cat.{}.jpg'.format(i) for i in range(1000,2000)]
    for fname in fnames:
        src = os.path.join(dc_dir, fname)
        dst = os.path.join(train_cat_dir, fname)
        shutil.copyfile(src, dst)
    #
    fnames = ['cat.{}.jpg'.format(i) for i in range(1000, 1500)]
    for fname in fnames:
        src = os.path.join(dc_dir, fname)
        dst = os.path.join(test_cat_dir, fname)
        shutil.copyfile(src, dst)

    fnames = ['dog.{}.jpg'.format(i) for i in range(1000)]
    for fname in fnames:
        src = os.path.join(dc_dir, fname)
        dst = os.path.join(train_dog_dir, fname)
        shutil.copyfile(src, dst)

    fnames = ['dog.{}.jpg'.format(i) for i in range(1000, 1500)]
    for fname in fnames:
        src = os.path.join(dc_dir, fname)
        dst = os.path.join(test_dog_dir, fname)
        shutil.copyfile(src, dst)

#%%

from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)

#%%

train_generator = train_datagen.flow_from_directory(
    train_dir,
    target_size=(200, 200),
    batch_size=20,
    class_mode='binary'
)

test_generator = test_datagen.flow_from_directory(
    test_dir,
    target_size=(200, 200),
    batch_size=20,
    class_mode='binary'
)

#%% md

# keras內建經典網路實現

#%%
covn_base = VGG16(weights=None, include_top=False)


#%%

covn_base.summary()

#%%

model = keras.Sequential()
model.add(covn_base)
model.add(layers.GlobalAveragePooling2D())
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

#%%

model.summary()

#%%

covn_base.trainable = False #設定權重不可變,卷積基不可變

#%%

model.summary()

#%%
model.compile(optimizer=Adam(lr=0.001),
              loss='binary_crossentropy',
              metrics=['acc'])


#%%

history = model.fit_generator(
    train_generator,
    steps_per_epoch=100,
    epochs=15,
    validation_data=test_generator,
    validation_steps=50)

#%%

import matplotlib.pyplot as plt
# %matplotlib inline

#%%
print(history.history)

plt.plot(history.epoch, history.history['loss'], 'r', label='loss')
# plt.plot(history.epoch, history.history['val_loss'], 'b--', label='val_loss')
plt.legend()

#%%

plt.plot(history.epoch, history.history['acc'], 'r')
# plt.plot(history.epoch, history.history['val_acc'], 'b--')

相關文章