我下载了微型 imagenet 数据集,它是 imagenet 数据集的子集,其图像大小为 64*64 像素。我想在原始 imagenet 上使用预训练模型,例如 alexnet 和 VGG,并将微型 imagenet 的图像作为网络的输入。这是真的还是假的? 如您所知,原始 ImageNet 中图像的分辨率高于微型 ImageNet。它会导致推理任务出现问题吗? 感谢您的关注。
最佳答案
通常,CNN 层可用于任何大小的图像。 CNN 层中的权重数量不取决于图像大小,而是取决于核的数量和形状。因此,例如:
Conv2D(16, (3, 3), padding="same",input_shape=(None, None, 3))
始终有 16(内核)* 3 * 3 * 3( channel )+ 16(偏差)= 448 个权重。
唯一的问题是网络的头部通常是一组具有固定数量输入的密集层。因此,如果您只是在 Conv2D
和 Dense
层之间展平
网络,则图像的大小必须是固定的。但是,如果您放置例如 tf.keras.layers.GlobalAveragePooling2D 层,则图像的大小可能会发生变化,因为该层生成的输出仅取决于内核的数量,而不取决于图像的大小。
如果您使用带头的版本(include_top
参数):
base_model = tf.keras.applications.VGG16(weights = 'imagenet', include_top = True)
或
base_model = tf.keras.applications.MobileNet(weights = 'imagenet', include_top = True)
您可以使用base_model.summary()
检查他们期望的图像大小为(224,224,3)。
但如果您像这样添加 include_top=False
:
base_model = tf.keras.applications.VGG16(weights = 'imagenet', include_top = False)
图像的预期input_shape
为(None, None, 3)
。这样的网络对于大小为 (W, H, 3)
的图像产生大小为 (W/S, H/S, K)
的输出,其中 K 是数字最后一层的核数,S 是特定网络的收缩因子。例如,对于 VGG16 网络 S=32 和 K=512,因此对于大小为 (224,224,3) 的图像,输出大小为 (7,7,512),对于大小为 (512,512,3) 的图像,输出为 (16,16,512) 。这样的输出有时称为“补丁”。
因此,如果您想构建使用某些预训练网络并对任意大小的图像进行分类的网络,您可以像这样构建:
base_model = tf.keras.applications.ResNet50(weights = 'imagenet', include_top = False)
x = base_model.output
x = tf.keras.layers.GlobalAveragePooling2D()(x)
x = tf.keras.layers.Dense(512, activation = 'relu')(x)
...
last_layer = tf.keras.layers.Dense(num_classes, activation = 'softmax')(x)
model = tf.keras.models.Model(inputs = base_model.input, outputs = last_layer)
这样的模型可以输入任意大小的图像,并生成num_classes
类的概率向量。当然,在训练过程中,您必须在一批中使用相同大小的图像,但之后您可以使用任何图像。
关于keras - 如何在低分辨率图像(例如小型 imagenet 数据集)上使用预训练模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66949080/