記事ディレクトリ
Keras の事前トレーニング済みモデルを使用した完全な猫と犬の認識
VGG16 は、2014 年にオックスフォード大学コンピューター ビジョン研究グループによって提案された深層畳み込みニューラル ネットワークです。ImageNet 画像認識コンテストのチャンピオンであり、より優れた画像認識と分類効果を備えています。VGG16 のアーキテクチャは非常にシンプルで、特徴抽出部は 13 層の畳み込み層と 5 層のプーリング層で構成され、分類器部は 3 層の全結合層で構成されています。VGG16 のコンボリューション層はすべて 3×3 のコンボリューション カーネル、プーリング層は最大 2×2 のプーリングであり、層ごとにコンボリューション カーネルの数が増加して、より複雑な特徴を抽出します。
VGG16 は、特徴抽出と分類の 2 つの部分に分けることができます。特徴抽出部分には 13 の畳み込み層と 5 つのプーリング層が含まれます。最初の 12 の畳み込み層は 2 つの畳み込み層と 1 つのプーリング層で構成され、各畳み込み層は 64 個の畳み込みカーネルを持ち、活性化関数は ReLU です。この設計により、VGG16 の特徴抽出機能がより強力になり、より複雑な特徴を抽出できるようになります。13 番目の畳み込み層は 512 個の畳み込みカーネルを持ち、活性化関数も ReLU であり、この層の機能は画像の特徴をより深く抽象化することです。特徴抽出部分の後に、VGG16 には分類器部分、つまり 3 つの全結合層も含まれており、最初の全結合層には 4096 個のノードがあり、2 番目の全結合層にも 4096 個のノードがあります。最後の完全に接続された層には 1000 個のノードがあり、ImageNet の 1000 カテゴリに対応します。
VGG16 の利点は、優れたパフォーマンスを備えていることですが、多くのモデル パラメーターがあり、大規模な記憶領域とコンピューティング リソースを必要とすることです。この問題に対応して、VGG16 の作成者は、VGG16 に基づいていくつかの畳み込み層とプーリング層を追加する VGG19 モデルを提案しましたが、このモデルにはより多くのパラメーターがあり、より多くのコンピューティング リソースを消費します。
一般に、VGG16 は強力な特徴抽出機能を備えたシンプルで効果的な深層畳み込みニューラル ネットワークであり、画像の特徴情報を効果的に抽出し、より優れた画像認識および分類効果を得ることができます。
1. Keras ライブラリをインポートする
from keras import layers
import tensorflow as tf
import keras
import numpy as np
import os
import shutil
import warnings
warnings.filterwarnings('ignore')
Using TensorFlow backend.
2. データセットをインポートする
base_dir = './dataset/cat_dog'
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 = './dataset/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)]
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'
)
Found 2000 images belonging to 2 classes.
Found 1000 images belonging to 2 classes.
3. Keras 組み込みのクラシック ネットワークの実装
covn_base = keras.applications.VGG16(weights=None, include_top=False)
WARNING:tensorflow:From /home/nlp/anaconda3/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:4070: The name tf.nn.max_pool is deprecated. Please use tf.nn.max_pool2d instead.
covn_base.summary()
Model: "vgg16"
_________________________________________________________________
Layer (type) Output Shape Param #
_________________________________________________________________
input_1 (InputLayer) (None, None, None, 3) 0
_________________________________________________________________
block1_conv1 (Conv2D) (None, None, None, 64) 1792
_________________________________________________________________
block1_conv2 (Conv2D) (None, None, None, 64) 36928
_________________________________________________________________
block1_pool (MaxPooling2D) (None, None, None, 64) 0
_________________________________________________________________
block2_conv1 (Conv2D) (None, None, None, 128) 73856
_________________________________________________________________
block2_conv2 (Conv2D) (None, None, None, 128) 147584
_________________________________________________________________
block2_pool (MaxPooling2D) (None, None, None, 128) 0
_________________________________________________________________
block3_conv1 (Conv2D) (None, None, None, 256) 295168
_________________________________________________________________
block3_conv2 (Conv2D) (None, None, None, 256) 590080
_________________________________________________________________
block3_conv3 (Conv2D) (None, None, None, 256) 590080
_________________________________________________________________
block3_pool (MaxPooling2D) (None, None, None, 256) 0
_________________________________________________________________
block4_conv1 (Conv2D) (None, None, None, 512) 1180160
_________________________________________________________________
block4_conv2 (Conv2D) (None, None, None, 512) 2359808
_________________________________________________________________
block4_conv3 (Conv2D) (None, None, None, 512) 2359808
_________________________________________________________________
block4_pool (MaxPooling2D) (None, None, None, 512) 0
_________________________________________________________________
block5_conv1 (Conv2D) (None, None, None, 512) 2359808
_________________________________________________________________
block5_conv2 (Conv2D) (None, None, None, 512) 2359808
_________________________________________________________________
block5_conv3 (Conv2D) (None, None, None, 512) 2359808
_________________________________________________________________
block5_pool (MaxPooling2D) (None, None, None, 512) 0
_________________________________________________________________
Total params: 14,714,688
Trainable params: 14,714,688
Non-trainable params: 0
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()
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
_________________________________________________________________
vgg16 (Model) (None, None, None, 512) 14714688
_________________________________________________________________
global_average_pooling2d_1 ( (None, 512) 0
_________________________________________________________________
dense_1 (Dense) (None, 512) 262656
_________________________________________________________________
dense_2 (Dense) (None, 1) 513
_________________________________________________________________
Total params: 14,977,857
Trainable params: 14,977,857
Non-trainable params: 0
covn_base.trainable = False #设置权重不可变,卷积基不可变
model.summary()
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
_________________________________________________________________
vgg16 (Model) (None, None, None, 512) 14714688
_________________________________________________________________
global_average_pooling2d_1 ( (None, 512) 0
_________________________________________________________________
dense_1 (Dense) (None, 512) 262656
_________________________________________________________________
dense_2 (Dense) (None, 1) 513
_________________________________________________________________
Total params: 14,977,857
Trainable params: 263,169
Non-trainable params: 14,714,688
model.compile(optimizer=keras.optimizers.Adam(lr=0.001),
loss='binary_crossentropy',
metrics=['acc'])
WARNING:tensorflow:From /home/nlp/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/nn_impl.py:180: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
4. トレーニングモデル
history = model.fit_generator(
train_generator,
steps_per_epoch=10,
epochs=15,
validation_data=test_generator,
validation_steps=50)
WARNING:tensorflow:From /home/nlp/anaconda3/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py:422: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.
Epoch 1/15
9/10 [==========================>...] - ETA: 5s - loss: 0.6912 - acc: 0.5500
……
5. 解析モデル
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(history.epoch, history.history['loss'], 'r', label='loss')
plt.plot(history.epoch, history.history['val_loss'], 'b--', label='val_loss')
plt.plot(history.epoch, history.history['acc'], 'r')
plt.plot(history.epoch, history.history['val_acc'], 'b--')
plt.legend()