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.ToTensor(),
transforms.RandomRotation(degrees = 5),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])

def show_images(img):
plt.imshow(transforms.functional.to_pil_image(img))
plt.show()

Check my own x-ray chest image

image_valid = Image.open(‘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 = image_valid.to(device)
model.to(device)
model.eval()
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’)
else:
print(‘Something wrong with binary classification - check twice’)

show_images(image_valid)

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:

7 Likes

It helps! Thank you very much!

1 Like

thank youIt helps! Thank you very much!

1 Like