LoginSignup
2
3

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-09-09

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

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

参考のスクリプトは
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)追加する出力層を作成
fc_model = Sequential()
fc_model.add(Flatten(input_shape=vgg16_model.output_shape[1:]))
fc_model.add(Dense(1024,activation='relu'))
fc_model.add(Dense(5,activation='softmax'))

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

# モデル表示
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)追加する出力層を作成

fc_model」(任意設定)という空のモデルを作成

fc_model = Sequential()

全結合層に入れるために平準化()します
下記の例では接続する「VGG16_model」の出口のshapeを取得するようにしています

自分で指示もできますが、接続元(vgg16_model)のshapeと違っていると
モデルを接続することができませんので、接続元からshapeを取得するほうがオススメです

fc_model.add(Flatten(input_shape=vgg16_model.output_shape[1:]))

1024次元の全結合レイヤーを作成(活性化関数は'Relu')

fc_model.add(Dense(1024,activation='relu'))

5クラス分類の全結合レイヤーを作成

fc_model.add(Dense(5,activation='softmax'))

3) VGG16と出力層を接続

kerasの1.0と2.0で書式が違うようで、書き方によっては警告が出ます
とりあえずこれは出ないので問題はなさそうです・・・

model = Model(inputs=vgg16_model.input, outputs=fc_model(vgg16_model.output))
2
3
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
3