2

我正在尝试使用我的自定义数据修改 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)

请帮忙。谢谢!

4

1 回答 1

5

1.首先,了解错误。

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

2. 然后,你能做什么。

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

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.
于 2018-03-09T19:01:06.683 回答