我對深度學習和影像分類有點陌生。我想使用 VGG16 從影像中提取特征并將它們作為輸入提供給我的 vit-keras 模型。以下是我的代碼:
from tensorflow.keras.applications.vgg16 import VGG16
vgg_model = VGG16(include_top=False, weights = 'imagenet', input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))
for layer in vgg_model.layers:
layer.trainable = False
from vit_keras import vit
vit_model = vit.vit_b16(
image_size = IMAGE_SIZE,
activation = 'sigmoid',
pretrained = True,
include_top = False,
pretrained_top = False,
classes = 2)
model = tf.keras.Sequential([
vgg_model,
vit_model,
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation = tfa.activations.gelu),
tf.keras.layers.Dense(256, activation = tfa.activations.gelu),
tf.keras.layers.Dense(64, activation = tfa.activations.gelu),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(1, 'sigmoid')
],
name = 'vision_transformer')
model.summary()
但是,我收到以下錯誤:
ValueError:層嵌入的輸入 0 與層不兼容:輸入形狀的預期軸 -1 具有值 3,但接收到的輸入具有形狀(無、8、8、512)
我假設這個錯誤發生在 VGG16 和 vit-keras 的合并中。在這種情況下如何糾正這個錯誤?
uj5u.com熱心網友回復:
您不能將VGG16模型的輸出提供給vit_model,因為兩個模型都需要輸入形狀(224, 224, 3)或您定義的某些形狀。問題是VGG16模型具有輸出形狀(8, 8, 512)。您可以嘗試對輸出進行上采樣/重塑/調整大小以適應預期的形狀,但我不推薦這樣做。相反,只需將相同的輸入提供給兩個模型,然后將它們的結果連接起來。這是一個作業示例:
import tensorflow as tf
import tensorflow_addons as tfa
from vit_keras import vit
IMAGE_SIZE = 224
vgg_model = tf.keras.applications.vgg16.VGG16(include_top=False, weights = 'imagenet', input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))
for layer in vgg_model.layers:
layer.trainable = False
vit_model = vit.vit_b16(
image_size = IMAGE_SIZE,
activation = 'sigmoid',
pretrained = True,
include_top = False,
pretrained_top = False,
classes = 2)
inputs = tf.keras.layers.Input((IMAGE_SIZE, IMAGE_SIZE, 3))
vgg_output = tf.keras.layers.Flatten()(vgg_model(inputs))
vit_output = vit_model(inputs)
x = tf.keras.layers.Concatenate(axis=-1)([vgg_output, vit_output])
x = tf.keras.layers.Dense(512, activation = tfa.activations.gelu)(x)
x = tf.keras.layers.Dense(256, activation = tfa.activations.gelu)(x)
x = tf.keras.layers.Dense(64, activation = tfa.activations.gelu)(x)
x = tf.keras.layers.BatchNormalization()(x)
outputs = tf.keras.layers.Dense(1, 'sigmoid')(x)
model = tf.keras.Model(inputs, outputs)
print(model.summary())
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/437202.html
