简体   繁体   中英

ValueError: Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (6243, 256, 256)

I want to append the label on the training dataset and I do it as

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

However, the error returned when execute the input on 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)))

Can anyone help me to fix it?

Your input layer is expecting an array of shape (batch_size, 256, 256, 1) but it looks like you are passing in data of the shape (batch_size, 256, 256) . You can try reshaping your training data as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM