【问题标题】:Uncaught Error: Error when checking : expected conv2d_input to have 4 dimension(s), but got array with shape [275,183,3]未捕获的错误:检查时出错:预期 conv2d_input 有 4 个维度,但得到了形状为 [275,183,3] 的数组
【发布时间】:2018-10-29 20:27:49
【问题描述】:

在训练我的 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 中

预测代码sn-p

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

我收到以下错误:

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

把上面的代码改成

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

给出以下错误:

未捕获的错误:检查时出错:预期 conv2d_input 有 4 维度,但得到了形状为 [50,50,1] 的数组

最后,当我这样做时

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

我收到以下错误:

检查时出错:预期 conv2d_input 具有形状 [null,50,50,1] 但得到了形状为 [1,50,50,3] 的数组。

【问题讨论】:

    标签: python tensorflow conv-neural-network tensorflow.js


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-04
        • 2020-09-06
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 1970-01-01
        • 1970-01-01
        • 2019-07-31
        相关资源
        最近更新 更多