Keras特征提取-预期输入_1有4个维度,但得到了形状为(1,46)的数组

Keras特征提取-预期输入_1有4个维度,但得到了形状为(1,46)的数组,keras,vgg-net,Keras,Vgg Net,在提取图像特征时,我对Keras有一个问题。 我已经添加了4d层 使用此代码 # Add a fourth dimension (since Keras expects a list of images) image_array = np.expand_dims(image_array, axis=0) 但还是给了我一个错误 这是我的实际代码: from pathlib import Path import numpy as np import joblib from keras.prepro

在提取图像特征时,我对Keras有一个问题。 我已经添加了4d层 使用此代码

# Add a fourth dimension (since Keras expects a list of images)
image_array = np.expand_dims(image_array, axis=0)
但还是给了我一个错误

这是我的实际代码:

from pathlib import Path
import numpy as np
import joblib
from keras.preprocessing import image
from keras.applications import vgg16
import os.path

# Path to folders with training data
img_db = Path("database") / "train"

images = []
labels = []

# Load all the not-dog images
for file in img_db.glob("*/*.jpg"):

    file = str(file)

    # split path with filename
    pathname, filename = os.path.split(file)
    person = pathname.split("\\")[-1]

    print("Processing file: {}".format(file))

    # Load the image from disk
    img = image.load_img(file)

    # Convert the image to a numpy array
    image_array = image.img_to_array(img)

    # Add a fourth dimension (since Keras expects a list of images)
    # image_array = np.expand_dims(image_array, axis=0)

    # Add the image to the list of images
    images.append(image_array)

    # For each 'not dog' image, the expected value should be 0
    labels.append(person)

# Create a single numpy array with all the images we loaded
x_train = np.array(images)

# Also convert the labels to a numpy array
y_train = np.array(labels)

# Normalize image data to 0-to-1 range
x_train = vgg16.preprocess_input(x_train)

input_shape = (250, 250, 3)
# Load a pre-trained neural network to use as a feature extractor
pretrained_nn = vgg16.VGG16(weights='imagenet', include_top=False, input_shape=input_shape)

# Extract features for each image (all in one pass)
features_x = pretrained_nn.predict(x_train)

# Save the array of extracted features to a file
joblib.dump(features_x, "x_train.dat")

# Save the matching array of expected values to a file
joblib.dump(y_train, "y_train.dat")
错误

回溯(最近一次呼叫最后一次): 文件 “C:/Users/w024029h/pycharm项目/keras_pretrained/pretrained_vgg16.py”, 第57行,在 features\u x=pretrained\u nn.predict(x\u train)文件“C:\Users\w024029h\AppData\Local\Programs\Python\Python36\lib\site packages\keras\engine\training.py”, 第1817行,在预测中 检查\u batch\u axis=False)文件“C:\Users\w024029h\AppData\Local\Programs\Python\Python36\lib\site packages\keras\engine\training.py”, 第113行,输入数据 “with shape”+str(data_shape))ValueError:检查时出错:预期输入_1有4个维度,但得到了形状为(1, (46)


添加额外维度后,
image\u数组
的形状类似于
(1,3,250,250)
(1,250,250,3)
(取决于您的后端,考虑到三通道图像)

当您执行
images.append(image\u array)
时,它会将这个4d数组追加到numpy数组列表中。实际上,该列表将是一个5d数组,但当您将该列表转换回numpy数组时,numpy无法知道所需的尺寸形状/数量

您可以使用
np.vstack()

更改代码中的以下行:

# Create a single numpy array with all the images we loaded
x_train = np.array(images)
用于:

x_train = np.vstack(images)