如何在keras2.0中使用InceptionV3瓶颈作为输入

2024-04-26 14:38:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Keras中使用InceptionV3来使用瓶颈进行迁移学习。 我使用了一些关于创建、加载和使用瓶颈的技巧 https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html

我的问题是我不知道如何使用瓶颈(numpy数组)作为具有新顶层的InceptionV3的输入。在

我得到以下错误:

ValueError: Error when checking input: expected input_3 to have shape (None, None, None, 3) but got array with shape (248, 8, 8, 2048)

248表示本例中的图像总数。在

我知道这条线是错的,但我不知道如何纠正它:

model = Model(inputs=base_model.input, outputs=predictions)

在InceptionV3中输入瓶颈的正确方法是什么?在

创建InceptionV3瓶颈:

^{1}$

加载瓶颈:

^{pr2}$

开始培训:

def start_training():
global nb_train_samples, nb_validation_samples

create_bottlenecks()

train_data, train_labels = load_bottlenecks(train_data_dir, train_bottlenecks_file)
validation_data, validation_labels = load_bottlenecks(validation_data_dir, validation_bottlenecks_file)

nb_train_samples = len(train_data)
nb_validation_samples = len(validation_data)

base_model = InceptionV3(weights='imagenet', include_top=False)

# add a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)

# let's add a fully-connected layer
x = Dense(1024, activation='relu')(x)

# and a logistic layer -- let's say we have 2 classes
predictions = Dense(2, activation='softmax')(x)

# What is the correct input? Obviously not base_model.input.
model = Model(inputs=base_model.input, outputs=predictions)

# first: train only the top layers (which were randomly initialized)
# i.e. freeze all convolutional InceptionV3 layers
for layer in base_model.layers:
    layer.trainable = False

model.compile(optimizer=optimizers.SGD(lr=0.01, momentum=0.9), loss='categorical_crossentropy', metrics=['accuracy'])

# train the model on the new data for a few epochs
history = model.fit(train_data, train_labels,
                    epochs=epochs,
                    batch_size=batch_size,
                    validation_data=(validation_data, validation_labels),
)

任何帮助都将不胜感激!在


Tags: thenonelayerinputdatabaselabelsmodel
1条回答
网友
1楼 · 发布于 2024-04-26 14:38:14

当您尝试使用与模型支持的形状不同的输入数据来训练模型时,会发生此错误。在

您的模型支持(None, None, None, 3),这意味着:

  • 任意数量的图像
  • 任何高度
  • 任何宽度
  • 3个通道

因此,必须确保train_data(和validation_data)与此形状匹配。在

系统显示train_data.shape = (248,8,8,2048)

我看到train_data来自load_botlenecks。它真的应该是从那里来的吗?列车数据应该是什么?一个图像?还有别的事吗?什么是瓶颈?在


您的模型从Inception模型开始,并且Inception模型获取图像。在

但是,如果瓶颈已经是初始模型的结果,并且您只想为提供瓶颈,那么初始模型就不应该参与任何事情。在

开始时间:

inputTensor = Input((8,8,2048)) #Use (None,None,2048) if bottlenecks vary in size    
x = GlobalAveragePooling2D()(inputTensor)

.....

使用以下内容创建模型:

^{pr2}$

其理念是:

  • 初始模型:映像->初始->瓶颈
  • 您的模型:瓶颈->模型->标签

只有在没有预先加载瓶颈的情况下,这两个模型的组合才是必需的,但是您有自己的图像,您想首先预测瓶颈。(当然,您也可以使用不同的模型)

然后您只需要输入图像(瓶颈将由Inception创建并传递给您的模型,内部的所有内容):

  • 组合模型:图像->初始->瓶颈->模型->标签

为此:

inputImage = Input((None,None,3))
bottleNecks = base_model(inputImage)
predictions = model(bottleNecks)

fullModel = Model(inputImage, predictions)

相关问题 更多 >