使用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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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