使用 model.predict() 后如何理解结果数组的维度

How to understand the dimensions of the result array after using model.predict()

我正在重复一个代码来检索项目,但是当我在 model.predict 函数中调试时,我发现这个函数的输入是维度 (1, 224, 224, 3),但输出是 (1, 7, 7, 2048)。 model.predict() 的结果不应该是一个一维数组,它给出了对象属于每个类别而不是 4D 的概率吗?如何理解这个结果数组的维度?

    model_features = model.predict(x, batch_size=1)

具体代码如下: (这只是整个代码的一部分,可能不会直接运行)

import keras.applications.resnet50
import numpy as np
import os
import pickle
import time
import vse
from keras.preprocessing import image
from keras.models import Model, load_model

model = keras.applications.resnet50.ResNet50(include_top=False)
model_extension == "resnet"

def extract_features_cnn(img_path):
    """Returns a normalized features vector for image path and model specified in parameters file """
    print('Using model', model_extension)
    img = image.load_img(img_path, target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    if model_extension == "vgg19":
        x = keras.applications.vgg19.preprocess_input(x)
    elif model_extension == "vgg16":
        x = keras.applications.vgg16.preprocess_input(x)
    elif model_extension == "resnet":
        x = keras.applications.resnet50.preprocess_input(x)
    else:
        print('Wrong model name')
    model_features = model.predict(x, batch_size=1)
    x = model_features[0]
    total_sum = sum(model_features[0])
    features_norm = np.array([val / total_sum for val in model_features[0]], dtype=np.float32)
    if model_extension == "resnet":
        print("reshaping resnet")
        features_norm = features_norm.reshape(2048, -1)
    return features_norm

你的问题不够清楚,我会尽量解释清楚你的问题。您的模型只有 ResNet,它只有卷积层,没有线性层,线性层可能导致表示 classes 概率的结果。你的结果不是你想象的 4D。在 (1, 7, 7, 2048) 的输出形状中,1 表示批量大小。这意味着您只向网络提供了 1 张图像并获得了 1 个结果。 7s 代表您的输出尺寸为 7x7。 2048代表你的输出通道。如果你想有classes的概率你需要在ResNet网络的最后添加一个线性层。您可以使用参数 include_top=True 添加它,您可以使用参数 classes=1000.

指定 class 数字

Here 是文档。