错误: 检查时出现错误:预期 conv2d_input 应为 4 维度,但得到的数组形状为 [275, 183, 3]

2024-09-28 23:33:36 发布

您现在位置:Python中文网/ 问答频道 /正文

在训练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)

我正在训练模特。以下是起始层:

^{pr2}$

我使用训练过的模型来得到一些预测(我用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].


Tags: topath模型imgfordatasizetraining
2条回答

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

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

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

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

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

相关问题 更多 >