為了制作一個漂亮的架構,我想將遷移學習模型一個接一個地堆疊起來。
我想堆疊的三個模型是:
- VGG16
- 盜夢空間V3
- 資源網50
因此,我將三個模型定義如下:
model_vgg = tf.keras.applications.VGG16(
weights='imagenet',
include_top=False,
input_shape=(SIZE, SIZE, 3)
)
model_inc = tf.keras.applications.inception_v3.InceptionV3(
weights='imagenet',
include_top=False,
input_shape=(SIZE, SIZE, 3)
)
model_res = tf.keras.applications.ResNet50(
weights='imagenet',
include_top=False,
input_shape=(SIZE, SIZE, 3)
)
大小設定為 100
在此之后,我trainable=False為他們每個人設定
現在,我將如何按順序堆疊這些模型,即我必須進行哪些更改以使每個模型的輸出形狀與下一個模型的輸入形狀匹配?
model = tf.keras.Sequential([
model_vgg,
model_inc,
model_res,
tf.keras.layers.Flatten()
])
uj5u.com熱心網友回復:
由于每個模型都有不同的輸出形狀,因此您必須在將每個模型輸入到下一個模型之前對其進行重塑,這可能會影響性能:
import tensorflow as tf
SIZE = 100
model_vgg = tf.keras.applications.VGG16(
weights='imagenet',
include_top=False,
input_shape=(SIZE, SIZE, 3)
)
model_inc = tf.keras.applications.inception_v3.InceptionV3(
weights='imagenet',
include_top=False,
input_shape=(SIZE, SIZE, 3)
)
model_res = tf.keras.applications.ResNet50(
weights='imagenet',
include_top=False,
input_shape=(SIZE, SIZE, 3)
)
model_vgg.trainable = False
model_inc.trainable = False
model_res.trainable = False
model = tf.keras.Sequential([
model_vgg,
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(SIZE*SIZE*3),
tf.keras.layers.Reshape((SIZE, SIZE, 3)),
model_inc,
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(SIZE*SIZE*3),
tf.keras.layers.Reshape((SIZE, SIZE, 3)),
model_res,
tf.keras.layers.Flatten()
])
print(model(tf.random.normal((1, 100, 100, 3))).shape)
您還必須決定是否要在每Dense一層上使用非線性激活函式。哦,你也可以像這樣使用每個模型的預處理方法:
model = tf.keras.Sequential([
tf.keras.layers.Lambda(lambda x: tf.keras.applications.vgg16.preprocess_input(x)),
model_vgg,
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(SIZE*SIZE*3),
tf.keras.layers.Reshape((SIZE, SIZE, 3)),
tf.keras.layers.Lambda(lambda x: tf.keras.applications.inception_v3.preprocess_input(x)),
model_inc,
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(SIZE*SIZE*3),
tf.keras.layers.Reshape((SIZE, SIZE, 3)),
tf.keras.layers.Lambda(lambda x: tf.keras.applications.resnet50.preprocess_input(x)),
model_res,
tf.keras.layers.Flatten()
])
我個人的建議是將輸入輸入到各個模型中,然后連接輸出并運行其他下游操作:
inputs = tf.keras.layers.Input((SIZE, SIZE, 3))
vgg = tf.keras.layers.Lambda(lambda x: tf.keras.applications.vgg16.preprocess_input(x))(inputs)
vgg = tf.keras.layers.GlobalAvgPool2D()(model_vgg(vgg))
inc = tf.keras.layers.Lambda(lambda x: tf.keras.applications.inception_v3.preprocess_input(x))(inputs)
inc = tf.keras.layers.GlobalAvgPool2D()(model_inc(inc))
res = tf.keras.layers.Lambda(lambda x: tf.keras.applications.resnet50.preprocess_input(x))(inputs)
res = tf.keras.layers.GlobalAvgPool2D()(model_res(res))
outputs = tf.keras.layers.Concatenate(axis=-1)([vgg, inc, res])
model = tf.keras.Model(inputs, outputs)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/415552.html
標籤:
