ValueError: expected 4D input (got 3D input)

Hello, guys! I am trying to check my trained model, but when I run my code I got a mistake which I can`t solve for few hours.

Maybe, someone have ideas what is wrong?

#Data preparation
preprocess = transforms.Compose([
transforms.Resize(size=(64, 64)),
transforms.RandomRotation(degrees = 5),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])

def show_images(img):

Check my own x-ray chest image

image_valid =‘Samofalov_xray_chest.jpeg’).convert(‘RGB’)
image_valid = preprocess(image_valid)

device = torch.device(“cuda:0” if torch.cuda.is_available() else “cpu”)

image_valid =
valid_result = model(image_valid)

if valid_result == 1:
print(f’Model says it is PNEUHMONIA’)
elif valid_result == 0:
print(f’Model says it is NORMAL’)
print(‘Something wrong with binary classification - check twice’)


Your model expects an input with 4 dimensions which correspond to BxCxHxW = (Batch x Channel x Height x Width).

Since you are testing it with only one image, you are missing the Batch (B) dimension.

To solve this, you can add this dimension by using unsqueeze

valid_result = model(image_valid.unsqueeze(0))

Hope this helps :smile:


It helps! Thank you very much!

1 Like

thank youIt helps! Thank you very much!

1 Like