Why there is not a simple way to display grid images in PyTorch?

israr_05: <p>I am new to PyTorch, I was using FastAi to solve some simple problems and now I want to learn PyTorch. I followed the procedure of and successfully loaded my dataset’s training and testing parts in data loader. I’ve applied some transformations as well before feeding to data loaders.<br>
Now, I want to display the batch of images before feeding to the Neural Networks. I’ve tried every possible solution to display the batch of images but no luck yet.<br>
I followed this <a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html" rel="noopener nofollow ugc">article</a> as well but still getting errors. Why there is not a simple method like Fastai to display batch images by one line of code?<br>
Can anyone guide me to use a method to display grid/batch images using PyTorch?<br>
Thank you in advance.</p>

Shisho_Sama: <p>Whats the error that you are getting?<br>
At the very least you could comeup with something like this :</p>
<pre><code class="lang-python">def visualize_imgs(imgs, labels, row=3, cols=11,):
    imgs = imgs.detach().numpy().transpose(0, 2,3,1)
    # now we need to unnormalize our images. 
    fig = plt.figure(figsize=(20,5))
    for i in range(imgs.shape[0]):
        ax = fig.add_subplot(row, cols, i+1, xticks=[], yticks=[])
        # if your images are 1 channel only, remove the channel dimension
        # so that matplotlib can work with it (e.g. change  28x28x1 to 28x28!)
        # like this ax.imshow(imgs[i].squeeze(), cmap='gray')
        ax.imshow(imgs[i])
        ax.set_title(labels[i].item())
    plt.show()
</code></pre>
<p>this should work as well, you may need to change it based on your needs, for example the rows, cols need to be set based on you batchsize. if you have normalized the inputs, unnormalize them as well.</p>

israr_05: <p>I am trying like this.</p>
<pre><code class="lang-auto">transf = transforms.Compose([transforms.Resize(255),
                             transforms.ToTensor(),
                             transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))
                            ])
</code></pre>
<pre><code class="lang-auto">trainloader = torch.utils.data.DataLoader(train_dataset, batch_size = 8, shuffle=True )
data_iter = iter(trainloader)
images, labels = next(data_iter)
fig, axes = plt.subplots(figsize = (10,4), ncols=4)
for ii in range(4):
    ax = axes[ii]
    helper.imshow(images[ii], ax=ax, normalize=False)
</code></pre>
<p>But getting this error</p>
<blockquote>
<p>RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 406 and 513 in dimension 3 at c:\a\w\1\s\tmp_conda_3.6_091443\conda\conda-bld\pytorch_1544087948354\work\aten\src\th\generic/THTensorMoreMath.cpp:1333</p>
</blockquote>

ptrblck: <p>The error seems to point to the <code>DataLoader</code>, which cannot stack tensors of different spatial shapes.<br>
Are you sure you are using the posted transformation?</p>

israr_05: <p>Yes, I am using the same transformations as I posted. Below is the screenshot of it.<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/4/3/432506cf04ce1565687a69c5db6bd39d07f896b8.png" data-download-href="https://discuss.pytorch.org/uploads/default/432506cf04ce1565687a69c5db6bd39d07f896b8" title="image"><img src="https://discuss.pytorch.org/uploads/default/original/3X/4/3/432506cf04ce1565687a69c5db6bd39d07f896b8.png" alt="image" data-base62-sha1="9zZjOGqtKCzqUZ4VEkcEgaMJvEQ" width="690" height="323" data-dominant-color="F0F1F1"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">722×338 11 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>I tried using <em><strong>transforms.Resize(256,256)</strong></em> also, but again it ends with an error which says I am using the value two times.</p>

ptrblck: <p>The error claims the height of the images is different as:</p>
<pre><code class="lang-python">Got 406 and 513 in dimension 3
</code></pre>
<p>so it seems the <code>Resize</code> is not used at all.<br>
Could you post the complete stack trace? Maybe the error isn’t raised by the <code>DataLoader</code> at all.</p>

israr_05: <p>Here is the complete code.</p>
<pre><code class="lang-auto">%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import torch
import torchvision
#import torchvision.transforms as transforms
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
import numpy as np
import helper
</code></pre>
<pre><code class="lang-auto">transf = transforms.Compose([transforms.Resize(255),

                             transforms.ToTensor(),

                             transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))

                            ])
</code></pre>
<pre><code class="lang-auto">datapath = 'raw-image2'
dataset = datasets.ImageFolder(datapath, transform=transf)

trains=int(0.7 * len(dataset))
tests=len(dataset)-trains

train_dataset, test_dataset =torch.utils.data.random_split(dataset, [trains, tests])  
trainload = torch.utils.data.DataLoader(train_dataset, batch_size=8, shuffle=True)
testload = torch.utils.data.DataLoader(test_dataset, batch_size = 8, shuffle=True)

trainload = torch.utils.data.DataLoader(train_dataset, batch_size = 8, shuffle=True )
testload = torch.utils.data.DataLoader(test_dataset, batch_size = 8, shuffle=True)

data_iter = iter(trainload)
images, labels = next(data_iter)
fig, axes = plt.subplots(figsize = (10,4), ncols=4)
for ii in range(4):
    ax = axes[ii]
    helper.imshow(images[ii], ax=ax, normalize=False)
</code></pre>
<p>This code I am using but no luck.</p>

ptrblck: <p>Unfortunately, I cannot debug more without seeing the actual stacktrace or any more debugging information about the images etc.<br>
Your code works using larger images as seen here:</p>
<pre><code class="lang-python">transf = transforms.Compose([transforms.Resize(255),
                             transforms.ToTensor(),
                             transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))
                            ])

dataset = datasets.FakeData(size=100, image_size=(3, 320, 480), transform=transf)

trains=int(0.7 * len(dataset))
tests=len(dataset)-trains

train_dataset, test_dataset = torch.utils.data.random_split(dataset, [trains, tests])  
trainload = torch.utils.data.DataLoader(train_dataset, batch_size=8, shuffle=True)
testload = torch.utils.data.DataLoader(test_dataset, batch_size = 8, shuffle=True)

data_iter = iter(trainload)
images, labels = next(data_iter)
fig, axes = plt.subplots(figsize = (10,4), ncols=4)
for ii in range(4):
    ax = axes[ii]
    ax.imshow(images[ii].permute(1, 2, 0))
</code></pre>