AttributeError: 'numpy.ndarray' object has no attribute 'unsqueeze'
I'm running a training code using pyhtorch and numpy.
This is the plot_example function:
def plot_example(low_res_folder, gen):
    files=os.listdir(low_res_folder)
    
    gen.eval()
    for file in files:
        image=Image.open(&quot;test_images/&quot; + file)
        with torch.no_grad():
            upscaled_img=gen(
                config1.both_transform(image=np.asarray(image))[&quot;image&quot;]
                .unsqueeze(0)
                .to(config1.DEVICE)
            )
        save_image(upscaled_img * 0.5 + 0.5, f&quot;saved/{file}&quot;)
    gen.train()

The problem I have is that the unsqueeze attribute raises the error:
File &quot;E:\Downloads\esrgan-tf2-masteren\modules\train1.py&quot;, line 58, in train_fn
    plot_example(&quot;test_images/&quot;, gen)
    
File &quot;E:\Downloads\esrgan-tf2-masteren\modules\utils1.py&quot;, line 46, in plot_example
    config1.both_transform(image=np.asarray(image))[&quot;image&quot;]
    
AttributeError: 'numpy.ndarray' object has no attribute 'unsqueeze'

The network is GAN network and gen() represents the Generator.

Make sure image is a tensor in the shape of [batch size, channels, height, width] before entering any Pytorch layers.
Here you have
image=np.asarray(image)
I would remove this numpy conversion and keep it a torch.tensor.
Or if you really want it to be a numpy array, then right before it enters your generator make sure to use torch.from_numpy() as shown in this documentation on your numpy image before it gets unsqueezed: https://pytorch.org/docs/stable/generated/torch.from_numpy.html
This function is ofcourse an alternative if you don't want to get rid of that original conversion.
Sarthak Jain
