NameError: name 'trainloader' is not defined

NameError Traceback (most recent call last)
in
21
22 # 학습용 이미지를 무작위로 가져오기
—> 23 dataiter = iter(trainloader)
24 images, labels = dataiter.next()
25

NameError: name ‘trainloader’ is not defined

This is a full error message. Pleae help.

This error is raised, if the variable trainloader is undefined. Often this could happen, if you have a typo in the name or the code logic is wrong, e.g. the trainloader is defined after its first usage.

Thanks for your answer.
but as you can see, ‘trainloader’ is defiend…
Also, I was running the example, not the code I wrote myself.

I don’t know what might be wrong with this code.
Could you post an executable code snippet to reproduce this issue?

[1]
import torch
import torchvision
import torchvision.transforms as transforms
import torch.utils.data as data
import torchvision.datasets as datasets
import torch.nn as nn

[2]
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

[3]
train_data = datasets.CIFAR10(root = “./data”,
train = True,
download = True,
transform = transform)

train_data, val_data = torch.utils.data.random_split(train_data, [int(len(train_data) * 0.8), int(len(train_data)*0.2)])

test_data = datasets.CIFAR10(root = “./data”,
train = False,
download = True,
transform = transform)

[4]
classes = test_data.classes
dic_classes = {}
for i in range(len(classes)):
dic_classes[i] = classes[i]

print(dic_classes)

[5]
trainloader = torch.utils.data.DataLoader(train_data, batch_size=16,
shuffle=True)
valloader = torch.utils.data.DataLoader(val_data, batch_size=16,
shuffle=True)
testloader = torch.utils.data.DataLoader(test_data, batch_size=16,
shuffle=False)

[6]
import matplotlib.pyplot as plt
import numpy as np

def imshow(img, labels, dic):
num = len(labels)
rows = int(np.sqrt(num))
cols = int(np.sqrt(num))

fig = plt.figure(figsize=(20,20))

for i in range(rows*cols):
    ax = fig.add_subplot(rows, cols, i+1)
    tmp = img[i]
    tmp = tmp / 2 + 0.5     # unnormalize
    npimg = tmp.numpy()
    ax.imshow(np.transpose(npimg, (1, 2, 0)), cmap = "bone")
    ax.title.set_text(dic[labels[i].item()])
    #plt.show()
    ax.axis('off')

학습용 이미지를 무작위로 가져오기

dataiter = iter(trainloader)
images, labels = dataiter.next()

이미지 보여주기

imshow(images, labels, dic_classes)

정답(label) 출력

‘[6]’ is issued code. I hope this helps.
[1]~[5] all worked normally. The mentioned error occurs in [6].

Thanks for the code.
Your code works fine on my machine. Here is the formatted code in case you want to rerun it:

import torch
import torchvision
import torchvision.transforms as transforms
import torch.utils.data as data
import torchvision.datasets as datasets
import torch.nn as nn


transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])


train_data = datasets.CIFAR10(
    root = "./data",
    train = True,
    download = True,
    transform = transform)

train_data, val_data = torch.utils.data.random_split(
    train_data, [int(len(train_data) * 0.8), int(len(train_data)*0.2)])

test_data = datasets.CIFAR10(
    root = "./data",
    train = False,
    download = True,
    transform = transform)


classes = test_data.classes
dic_classes = {}
for i in range(len(classes)):
    dic_classes[i] = classes[i]

print(dic_classes)

trainloader = torch.utils.data.DataLoader(
    train_data, batch_size=16, shuffle=True)
valloader = torch.utils.data.DataLoader(
    val_data, batch_size=16, shuffle=True)
testloader = torch.utils.data.DataLoader(
    test_data, batch_size=16, shuffle=False)


import matplotlib.pyplot as plt
import numpy as np

def imshow(img, labels, dic):
    num = len(labels)
    rows = int(np.sqrt(num))
    cols = int(np.sqrt(num))
    
    fig = plt.figure(figsize=(20,20))
    for i in range(rows*cols):
        ax = fig.add_subplot(rows, cols, i+1)
        tmp = img[i]
        tmp = tmp / 2 + 0.5     # unnormalize
        npimg = tmp.numpy()
        ax.imshow(np.transpose(npimg, (1, 2, 0)), cmap = "bone")
        ax.title.set_text(dic[labels[i].item()])
        #plt.show()
        ax.axis('off')

dataiter = iter(trainloader)
images, labels = dataiter.next()
imshow(images, labels, dic_classes)

I don’t get any errors and the sample images are displayed.

PS: you can post code snippets by warpping them into three backticks ```, which makes debugging easier. :wink: