使用CNN模型对图像进行预测时出现维度错误

我在使用Keras(2.2.4)及TensorFlow(1.9.0)作为后端对单张图像进行预测时遇到了问题:

def enigne(data):    img=data    image_shape=img.shape    num_train_samples = 4206    num_val_samples = 916    train_batch_size = 10    val_batch_size = 10    IMAGE_SIZE = 64    IMAGE_CHANNELS = 3    kernel_size = (3, 3)    pool_size = (2, 2)    first_filters = 32    second_filters = 128    image_resize=cv.resize(img,(64,64))    # 加载模型    model = Sequential()    model.add(Conv2D(first_filters, kernel_size, activation='relu', input_shape=(64, 64, 3)))    model.add(Conv2D(first_filters, kernel_size, activation='relu', kernel_regularizer=regularizers.l2(0.001))    model.add(Conv2D(second_filters, kernel_size, activation='relu', kernel_regularizer=regularizers.l2(0.001)))    model.add(MaxPooling2D(pool_size=pool_size))    model.add(Dropout(dropout_conv))    model.add(Flatten())    model.add(Dense(256, activation="relu"))    model.add(Dense(1, activation="sigmoid"))    model.compile(Adam(lr=0.0001), loss='binary_crossentropy',                  metrics=['accuracy'])    datagen = ImageDataGenerator(rescale=1.0 / 255)    model.load_weights('stableweights.h5')    y_pred_keras = model.predict_proba(image_resize)    p = []    for i in y_pred_keras:        for k in i:            if k <= 0.421:                p.append(0)            else:                p.append(1)    return p

我遇到了如下错误:

ValueError: Error when checking input: expected conv2d_input to have 4 dimensions, but got array with shape (64, 64, 3) 

如何将图像转换为合适的维度以输入到Keras模型中?


回答:

Keras模型期望输入的是样本批次。因此,您需要将第一个轴设置为批次轴:

Related Posts

在使用k近邻算法时,有没有办法获取被使用的“邻居”?

我想找到一种方法来确定在我的knn算法中实际使用了哪些…

Theano在Google Colab上无法启用GPU支持

我在尝试使用Theano库训练一个模型。由于我的电脑内…

准确性评分似乎有误

这里是代码: from sklearn.metrics…

Keras Functional API: “错误检查输入时:期望input_1具有4个维度,但得到形状为(X, Y)的数组”

我在尝试使用Keras的fit_generator来训…

如何使用sklearn.datasets.make_classification在指定范围内生成合成数据?

我想为分类问题创建合成数据。我使用了sklearn.d…

如何处理预测时不在训练集中的标签

已关闭。 此问题与编程或软件开发无关。目前不接受回答。…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注