Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

keras

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?

like image 930
AKF Avatar asked Dec 02 '25 13:12

AKF


1 Answers

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) 
like image 87
Anna Krogager Avatar answered Dec 05 '25 04:12

Anna Krogager



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!