繁体   English   中英

ValueError:`decode_predictions` 需要一批预测(即二维形状数组(样本,1000))。 找到形状为 (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需要一批预测(即一个二维形状数组(样本,1000))。 找到形状为 (1, 7) 的数组

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

我在 stackoverflow 上发现的一个类似问题( Keras: ValueError: decode_predictions expects a batch of predictions )建议在模型定义中包含 'inlcude_top=True' 来解决这个问题:

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

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

我怀疑您正在使用一些预先训练的模型,例如 resnet50 并且您正在导入decode_predictions ,如下所示:

from keras.applications.resnet50 import decode_predictions

decode_predictions 将 (num_samples, 1000) 个概率数组转换为原始 imagenet 类的类名。

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

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的情况下手动将类名分配给输出编号

'decode_predictions' 函数的重载。注释掉原始函数的 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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM