带有自定义数据的 Resnet

Resnet with Custom Data

我正在尝试使用我的自定义数据修改 Resnet50,如下所示:

X = [[1.85, 0.460,... -0.606] ... [0.229, 0.543,... 1.342]] 
y = [2, 4, 0, ... 4, 2, 2]

X是784张图片的长度为2000的特征向量。 y 是一个大小为 784 的数组,其中包含标签的二进制表示形式。

代码如下:

def __classifyRenet(self, X, y):
    image_input = Input(shape=(2000,1))
    num_classes = 5
    model = ResNet50(weights='imagenet',include_top=False)
    model.summary()
    last_layer = model.output
    # add a global spatial average pooling layer
    x = GlobalAveragePooling2D()(last_layer)
    # add fully-connected & dropout layers
    x = Dense(512, activation='relu',name='fc-1')(x)
    x = Dropout(0.5)(x)
    x = Dense(256, activation='relu',name='fc-2')(x)
    x = Dropout(0.5)(x)
    # a softmax layer for 5 classes
    out = Dense(num_classes, activation='softmax',name='output_layer')(x)

    # this is the model we will train
    custom_resnet_model2 = Model(inputs=model.input, outputs=out)

    custom_resnet_model2.summary()

    for layer in custom_resnet_model2.layers[:-6]:
        layer.trainable = False

    custom_resnet_model2.layers[-1].trainable

    custom_resnet_model2.compile(loss='categorical_crossentropy',
                                 optimizer='adam',metrics=['accuracy'])
    clf = custom_resnet_model2.fit(X, y,
                                    batch_size=32, epochs=32, verbose=1,
                                    validation_data=(X, y))
    return clf

我打电话的目的是:

clf = self.__classifyRenet(X_train, y_train)

报错:

ValueError: Error when checking input: expected input_24 to have 4 dimensions, but got array with shape (785, 2000)

请帮忙。谢谢!

1. First, understand the error.

你的输入与 ResNet 的输入不匹配,对于 ResNet,输入应该是 (n_sample, 224, 224, 3) 但你有 (785, 2000)。根据您的问题,您有 784 张图像,数组大小为 2000,无论您如何重塑它,它都不会真正与 (224 x 224) 的原始 ResNet50 输入形状对齐。这意味着您不能将 ResNet50 直接用于您的数据。您在代码中所做的唯一一件事就是采用 ResNet50 的最后一层并添加输出层以与输出 class 大小对齐。

2. Then, what you can do.

如果你坚持使用ResNet架构,你需要改变输入层而不是输出层。此外,您将需要重塑图像数据以利用卷积层。这意味着,你不能将它放在 (2000,) 数组中,而是需要像 (height, width, channel) 这样的数组,就像 ResNet 和其他架构正在做的那样。当然,您还需要像您所做的那样更改输出层,以便为您的 classes 进行预测。尝试类似的东西:

model = ResNet50(input_tensor=image_input_shape, include_top=True,weights='imagenet')

这样,您可以指定自定义的输入图像形状。您可以查看 github 代码以获取更多信息 (https://github.com/keras-team/keras/blob/master/keras/applications/resnet50.py)。这是文档字符串的一部分:

input_shape: optional shape tuple, only to be specified
    if `include_top` is False (otherwise the input shape
    has to be `(224, 224, 3)` (with `channels_last` data format)
    or `(3, 224, 224)` (with `channels_first` data format).
    It should have exactly 3 inputs channels,
    and width and height should be no smaller than 197.
    E.g. `(200, 200, 3)` would be one valid value.