ValueError:层 conv2d_46 的输入 0 与层不兼容:预期 min_ndim=4,发现 ndim=3。收到完整形状:(None, 64, 64)

时间:2021-05-21 10:43:01

标签: python tensorflow keras

我正在使用基于以下脚本的 (64, 64, 3) 形状的输入图像。我不确定为什么它会返回有关数据维度的错误。我也尝试过基于this posttrainX = tf.expand_dims(trainX, axis=-1),但是我无法解决。有人能帮我解决这个问题吗?

inputShape = (64, 64, 3)
chanDim = -1
# define the model input
inputs = Input(shape=inputShape)
# CONV => RELU => BN => POOL
x = Conv2D(16, (3, 3), padding="same")(inputs)
x = Activation("relu")(x)
x = BatchNormalization(axis=chanDim)(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
# CONV => RELU => BN => POOL
x = Conv2D(32, (3, 3), padding="same")(x)
x = Activation("relu")(x)
x = BatchNormalization(axis=chanDim)(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
# CONV => RELU => BN => POOL
x = Conv2D(64, (3, 3), padding="same")(x)
x = Activation("relu")(x)
x = BatchNormalization(axis=chanDim)(x)
x = MaxPooling2D(pool_size=(2, 2))(x)

# flatten the volume, then FC => RELU => BN => DROPOUT
x = Flatten()(x)
x = Dense(16)(x)
x = Activation("relu")(x)
x = BatchNormalization(axis=chanDim)(x)
x = Dropout(0.5)(x)

# apply another FC layer, this one to match the number of nodes
# coming out of the MLP
x = Dense(4)(x)
x = Activation("relu")(x)
x = Dense(1, activation="linear")(x)

# construct the CNN
model = Model(inputs, x)

model.summary()
fileToSaveModelPlot='model.png'
plot_model(model, to_file='model.png')
print("[INFO] Model plot saved to {}".format(fileToSaveModelPlot) )

opt = Adam(lr=1e-3, decay=1e-3 / 200)
model.compile(loss="mean_absolute_percentage_error", optimizer=opt)

history=model.fit(trainX, trainY, validation_data=(testX, testY),epochs=EPOCHS_NUM, batch_size=2)

错误:

ValueError: Input 0 of layer conv2d_46 is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (None, 64, 64)

-更新

#load csv file
labelPath =  "/content/drive/MyDrive/Notebook/tepm.csv"
cols = ["temperature"]
df = pd.read_csv(labelPath, sep=" ", header=None, names=cols)

inputPath='/content/drive/MyDrive/Notebook/test_png_64'
images = []

# Load in the images
for filepath in os.listdir(inputPath):
    images.append(cv2.imread(inputPath+'/{0}'.format(filepath),0))

images_scaled = np.array(images, dtype="float") / 255.0

这里是定义trainY、testY、trainX和testX的脚本

(trainY, testY, trainX, testX) = train_test_split(df, images_scaled, test_size=0.25, random_state=42)

这些是它们形状的代码和结果:

print (trainY.shape,testY.shape,trainX.shape, testX.shape)

(224, 1) (75, 1) (224, 64, 64) (75, 64, 64)

1 个答案:

答案 0 :(得分:0)

只需更改以下行:

images.append(cv2.imread(inputPath+'/{0}'.format(filepath)))

默认情况下,OpenCV 需要并读取彩色图像。使用 0 标志作为 cv2.imread 的参数而不是将图像加载为灰度图像,这会导致它具有单个颜色通道而不是 3 个颜色通道。