Uncaught Error: Error when checking : expected conv2d_input to have 4 dimension(s), but got array with shape [275,183,3]

Uncaught Error: Error when checking : expected conv2d_input to have 4 dimension(s), but got array with shape [275,183,3]

在训练我的 keras 模型之前,我对图像执行了以下操作:

for img in os.listdir(path):    
    # convert to array
    img_array = cv2.imread(os.path.join(path,img) ,cv2.IMREAD_GRAYSCALE) 
    # resize to normalize data size
    new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) 
    # add this to our training_data list
    training_data.append([new_array, class_num]) 

#shuffle the data 
random.shuffle(training_data)

#empty lists (X for features, y for labels)
X = []
y = []

for features,label in tqdm(training_data):
    X.append(features)
    y.append(label)


X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 1)

然后我正在训练模型。这是起始层:

#start creating model 
model = Sequential()

model.add(Conv2D(256, (3, 3), input_shape=X.shape[1:])

我正在使用经过训练的模型进行一些预测(我正在 python 中训练模型,然后将模型加载到 Tensorflow.js)

预测代码段

let imageTensor = tf.fromPixels(image);
model.predict(imageTensor).print();

我收到以下错误:

Uncaught Error: Error when checking : expected conv2d_input to have 4 dimension(s), but got array with shape [275,183,3]

将上面的代码改为

let imageTensor = tf.fromPixels(image).resizeNearestNeighbor([50,50]).mean(2).toInt().expandDims(2);
model.predict(imageTensor).print();

给出以下错误:

Uncaught Error: Error when checking : expected conv2d_input to have 4 dimension(s), but got array with shape [50,50,1]

最后,当我这样做时

let imageTensor = tf.fromPixels(image).resizeNearestNeighbor([50,50]).toInt().expandDims();
 model.predict(imageTensor).print();

我收到以下错误:

Error when checking : expected conv2d_input to have shape [null,50,50,1] but got array with shape [1,50,50,3].

在第一个示例中,对于 [256, (3,3) 和最后一件事],keras 在查找四个维度时将此列表视为具有三个维度或元素。删除括号以产生:

[256, 3, 3, input_shape=X.shape[1:]]

与模型输入的维度与作为参数传入预测方法的图像维度不匹配有关。

可以考虑按以下方式重塑图像:

imageTensor.reshape([-1, 50, 50, 3])