ValueError:检查输入时出错:预期input_1具有4个维,但数组的形状为(6243、256、256)

时间:2019-02-21 03:47:27

标签: python keras

我想将标签附加在训练数据集上,并且按如下操作

def one_hot_label(img):
    label = img
    if label == 'A':
        ohl = np.array([1, 0])
    elif label == 'B':
        ohl = np.array([0, 1])
    return ohl

def train_data_with_label():
    train_images = []
    for i in tqdm(os.listdir(train_data)):
        path_pre = os.path.join(train_data, i)
        for img in os.listdir(path_pre):
            if img.endswith('.jpg'):
                path = os.path.join(path_pre, img)
                img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
                train_images.append([np.array(img), one_hot_label(i)])
    shuffle(train_images)
    return train_images

但是,在Keras上执行输入时返回错误

training_images = train_data_with_label()
tr_img_data = np.array([i[0] for i in training_images])
tr_lbl_data = np.array([i[1] for i in training_images])

model = Sequential()
model.add(InputLayer(input_shape=(256, 256, 1)))

有人可以帮我修复它吗?

1 个答案:

答案 0 :(得分:3)

您的输入层期望使用形状为(batch_size, 256, 256, 1)的数组,但是您似乎正在传入形状为(batch_size, 256, 256)的数据。您可以尝试如下调整您的训练数据:

tr_img_data = np.expand_dims(tr_img_data, axis=-1)