LoginSignup
2
5

More than 5 years have passed since last update.

2つのモデルを接続する(keras2.0_functional 編)

Last updated at Posted at 2018-09-09

VGG16をFine-tuningする際に初めて作られる方も多いと思いますが
出力層の書き方が2種類あったりして分かりづらかったので
対で書きてみました

※Sequentialで出力層を書いたのはこちらから

参考のスクリプトは
VGG16をFine-tuningして5クラス分類するモデルを想定しています

動作概略

1)出力層なしのVGG16のモデルを読込
2)新しい出力層を作成
3)上記2個のモデルを接続

動作確認環境

python3.6.6
Tensorflow:1.10.0
Keras:2.2.2

参考スクリプト

#import
from keras.models import Model, Sequential
from keras.layers import Activation, Dense, Flatten
from keras.applications.vgg16 import VGG16

#1)出力層なしのVGG16を読込
vgg16_model = VGG16(weights='imagenet',include_top=False, input_tensor=Input(shape=(224,224,3)))

#2)追加する出力層を作成
inputs = vgg16_model.output
x = Flatten()(inputs)
x = Dense(1024,activation='relu')(x)

prediction = Dense(5,activation='softmax')(x)

#3) VGG16と出力層を接続
model=Model(inputs=vgg16_model.input,outputs=prediction)

# モデル表示
model.summary()

★解説

import

from keras.models import Model, Sequential
from keras.layers import Activation, Dense, Flatten
from keras.applications.vgg16 import VGG16

1)出力層なしのVGG16を読込

本題ではないので詳細は省略
引数の詳細は公式を確認してください
モデル名は「VGG16_model」(任意設定)とします

vgg16_model = VGG16(weights='imagenet',include_top=False, input_tensor=Input(shape=(224,224,3)))

2)追加する出力層を作成

vgg16_modelの出力を「inputs」(任意設定)に入力します

inputs = vgg16_model.output

全結合層に入れるために平準化します
inputs」に 「Flatten」を接続し「x」(任意設定)に入れます

x = Flatten()(inputs)

先ほどの「x」に1024次元の全結合レイヤーを接続し(活性化関数は'Relu')
再び「x」に入れます

x = Dense(1024,activation='relu')(x)

上記の「x」に、5クラス分類の全結合レイヤーを接続し「prediction」(任意設定)に入れます

prediction = Dense(10,activation='softmax')(x)

なんとなくこちらの書き方の方がさっぱりしています

3) VGG16と出力層を接続

これもfunctionalの方がさっぱりとしています

model=Model(inputs=vgg16_model.input,outputs=prediction)

全部「x」ではいけないのか?

「inputs」とか「prediction」とか使わないとダメなの?と疑問に思ったため
全部「x」で出来るかトライ・・・
結果としては何も問題ありません
(最初と最後をわかりやすくするため?)

vgg16_model = VGG16(weights='imagenet',include_top=False, input_tensor=Input(shape=(224,224,3)))

x = vgg16_model.output
x = Flatten()(x)
x = Dense(1024,activation='relu')(x)
x = Dense(10,activation='softmax')(x)

model=Model(inputs=vgg16_model.input,outputs=x)
2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5