ValueError: `decode_predictions` expects a batch of predictions (i.e. a 2D array of shape (samples, 1000)). Found array with shape: (1, 7)

ValueError: `decode_predictions` expects a batch of predictions (i.e. a 2D array of shape (samples, 1000)). Found array with shape: (1, 7)

我将 VGG16 与 keras 一起用于迁移学习(我的新模型中有 7 类),因此我想使用内置的 decode_predictions 方法来输出预测我的模型。但是,使用以下代码:

preds = model.predict(img)

decode_predictions(preds, top=3)[0]

我收到以下错误消息:

ValueError: decode_predictions expects a batch of predictions (i.e. a 2D array of shape (samples, 1000)). Found array with shape: (1, 7)

现在我想知道为什么在我的再训练模型中只有 7 类 时它期望 1000。

我在 Whosebug 上发现了一个类似的问题 ( ) 建议在模型定义中包含 'inlcude_top=True' 以解决此问题:

model = VGG16(weights='imagenet', include_top=True)

我已经试过了,但是它仍然没有用——给我和以前一样的错误。非常感谢任何有关如何解决此问题的提示或建议。

我怀疑您正在使用某些 pre-trained 模型,例如 resnet50 并且您正在导入 decode_predictions 像这样:

from keras.applications.resnet50 import decode_predictions

decode_predictions 将 (num_samples, 1000) 个概率的数组转换为 class 原始图像网络的名称 classes.

如果你想在 7 个不同的 class 之间转换学习和 classify,你需要这样做:

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

# add a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)
# add a fully-connected layer
x = Dense(1024, activation='relu')(x)
# and a logistic layer -- let's say we have 7 classes
predictions = Dense(7, activation='softmax')(x) 
model = Model(inputs=base_model.input, outputs=predictions)
...

拟合模型并计算预测后,您必须使用导入的 decode_predictions

手动将 class 名称分配给输出编号 而没有

重载 'decode_predictions' function.Comment 原始函数的 1000 类 约束:

CLASS_INDEX = None
@keras_modules_injection
def test_my_decode_predictions(*args, **kwargs):
    return my_decode_predictions(*args, **kwargs)


def my_decode_predictions(preds, top=5, **kwargs):
    global CLASS_INDEX

    backend, _, _, keras_utils = get_submodules_from_kwargs(kwargs)

    # if len(preds.shape) != 2 or preds.shape[1] != 1000:
    #     raise ValueError('`decode_predictions` expects '
    #                      'a batch of predictions '
    #                      '(i.e. a 2D array of shape (samples, 1000)). '
    #                      'Found array with shape: ' + str(preds.shape))
    if CLASS_INDEX is None:
        fpath = keras_utils.get_file(
            'imagenet_class_index.json',
            CLASS_INDEX_PATH,
            cache_subdir='models',
            file_hash='c2c37ea517e94d9795004a39431a14cb')
        with open(fpath) as f:
            CLASS_INDEX = json.load(f)
    results = []
    for pred in preds:
        top_indices = pred.argsort()[-top:][::-1]
        result = [tuple(CLASS_INDEX[str(i)]) + (pred[i],) for i in top_indices]
        result.sort(key=lambda x: x[2], reverse=True)
        results.append(result)
    return results


print('Predicted: ', test_my_decode_predictions(pred, top=10))