NameError: name 'trainloader' is not defined

111464: <p>NameError                                 Traceback (most recent call last)<br>
 in <br>
21<br>
22 # 학습용 이미지를 무작위로 가져오기<br>
—&gt; 23 dataiter = iter(trainloader)<br>
24 images, labels = dataiter.next()<br>
25</p>
<p>NameError: name ‘trainloader’ is not defined</p>
<p>This is a full error message. Pleae help.</p>

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

111464: <p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/1/1/11f9c55b16c5c65eef25d452992adf6bc9ea5601.jpeg" data-download-href="https://discuss.pytorch.org/uploads/default/11f9c55b16c5c65eef25d452992adf6bc9ea5601" title="캡처2"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/1/1/11f9c55b16c5c65eef25d452992adf6bc9ea5601_2_690x455.jpeg" alt="캡처2" data-base62-sha1="2z1fq6TDiH1IXhdvYsT4DsJBaNj" width="690" height="455" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/1/1/11f9c55b16c5c65eef25d452992adf6bc9ea5601_2_690x455.jpeg, https://discuss.pytorch.org/uploads/default/optimized/3X/1/1/11f9c55b16c5c65eef25d452992adf6bc9ea5601_2_1035x682.jpeg 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/1/1/11f9c55b16c5c65eef25d452992adf6bc9ea5601.jpeg 2x" data-dominant-color="F3F3F3"><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">캡처2</span><span class="informations">1138×751 80.1 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>Thanks for your answer.<br>
but as you can see, ‘trainloader’ is defiend…<br>
Also, I was running the example, not the code I wrote myself.</p>

ptrblck: <p>I don’t know what might be wrong with this code.<br>
Could you post an executable code snippet to reproduce this issue?</p>

111464: <p>[1]<br>
import torch<br>
import torchvision<br>
import torchvision.transforms as transforms<br>
import torch.utils.data as data<br>
import torchvision.datasets as datasets<br>
import torch.nn as nn</p>
<p>[2]<br>
transform = transforms.Compose(<br>
[transforms.ToTensor(),<br>
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])</p>
<p>[3]<br>
train_data = datasets.CIFAR10(root = “./data”,<br>
train = True,<br>
download = True,<br>
transform = transform)</p>
<p>train_data, val_data = torch.utils.data.random_split(train_data, [int(len(train_data) * 0.8), int(len(train_data)*0.2)])</p>
<p>test_data = datasets.CIFAR10(root = “./data”,<br>
train = False,<br>
download = True,<br>
transform = transform)</p>
<p>[4]<br>
classes = test_data.classes<br>
dic_classes = {}<br>
for i in range(len(classes)):<br>
dic_classes[i] = classes[i]</p>
<p>print(dic_classes)</p>
<p>[5]<br>
trainloader = torch.utils.data.DataLoader(train_data, batch_size=16,<br>
shuffle=True)<br>
valloader = torch.utils.data.DataLoader(val_data, batch_size=16,<br>
shuffle=True)<br>
testloader = torch.utils.data.DataLoader(test_data, batch_size=16,<br>
shuffle=False)</p>
<p>[6]<br>
import matplotlib.pyplot as plt<br>
import numpy as np</p>
<p>def imshow(img, labels, dic):<br>
num = len(labels)<br>
rows = int(np.sqrt(num))<br>
cols = int(np.sqrt(num))</p>
<pre><code>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')
</code></pre>
<h1>학습용 이미지를 무작위로 가져오기</h1>
<p>dataiter = iter(trainloader)<br>
images, labels = dataiter.next()</p>
<h1>이미지 보여주기</h1>
<p>imshow(images, labels, dic_classes)</p>
<h1>정답(label) 출력</h1>
<p>‘[6]’ is issued code. I hope this helps.<br>
[1]~[5] all worked normally. The mentioned error occurs in [6].</p>

ptrblck: <p>Thanks for the code.<br>
Your code works fine on my machine. Here is the formatted code in case you want to rerun it:</p>
<pre><code class="lang-python">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)
</code></pre>
<p>I don’t get any errors and the sample images are displayed.</p>
<p>PS: you can post code snippets by warpping them into three backticks ```, which makes debugging easier. <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=9" title=":wink:" class="emoji" alt=":wink:"></p>

Simeen_Bazel: <p>for images, labels in train_loader:<br>
pass</p>
<h1>
<a name="get-one-batch-1" class="anchor" href="#get-one-batch-1"></a>Get one batch</h1>
<p>images, labels = next(iter(train_loader))</p>
<p>indx=10<br>
plt.imshow(images[indx].reshape(64,64))<br>
plt.title(label_map[int(labels[indx].numpy())])</p>

Aneeqa_Mehrab: <p>Hello, I hope you are fine. I am facing the same issue “NameError: name ‘train_loader’ is not defined”, Here’s my code. Can you help me to resolve it. I will be very thankful to you.</p>
<p>"import argparse<br>
import os<br>
import pickle<br>
import time</p>
<p>import matplotlib.pyplot as plt<br>
import numpy as np<br>
import pandas as pd<br>
import PIL<br>
import torch<br>
import torch.optim as optim<br>
import torchvision<br>
from PIL import Image<br>
from torch import nn<br>
from torch.nn import functional as F</p>
<p>from datasets import QProper_signals1, QProper_signals2, QImproper_signals1, QImproper_signals2</p>
<h1><a name="p-461498-from-qvaebase-import-1" class="anchor" href="#p-461498-from-qvaebase-import-1"></a>from QVAE.base import *</h1>
<h1><a name="p-461498-from-qvaebase-import-basevae-2" class="anchor" href="#p-461498-from-qvaebase-import-basevae-2"></a>from QVAE.base import BaseVAE</h1>
<h1><a name="p-461498-from-qvaequaternion_layers-import-quaternionconv-quaternionlinear-3" class="anchor" href="#p-461498-from-qvaequaternion_layers-import-quaternionconv-quaternionlinear-3"></a>from QVAE.quaternion_layers import (QuaternionConv, QuaternionLinear,</h1>
<h1><a name="p-461498-quaterniontransposeconv-4" class="anchor" href="#p-461498-quaterniontransposeconv-4"></a>QuaternionTransposeConv)</h1>
<p>from models.vanilla_vae_q import QuaternionFCVAE2</p>
<p>parser = argparse.ArgumentParser()<br>
parser.add_argument(“–gpu_num”, type=int, default=0)<br>
parser.add_argument(“–track_signals”, type=bool, default=False)<br>
parser.add_argument(<br>
“–experiment”, type=int, default=3, help=“1, 2”<br>
)<br>
parser.add_argument(“–len_train”, type=int, default=1000)<br>
parser.add_argument(“–len_val”, type=int, default=500)<br>
parser.add_argument(“–n”, type=int, default=1)<br>
parser.add_argument(<br>
“–signal”, type=str, default=“improper”, help=“Either proper or improper.”<br>
)<br>
parser.add_argument(<br>
“–n_channels”,<br>
type=int,<br>
default=4,<br>
help=“3 for real-valued inputs, 4 for quaternion-valued inputs.”,<br>
)<br>
parser.add_argument(<br>
“–latent_dim”, type=int, default=100, help=“Dimension of the latent space.”<br>
)<br>
parser.add_argument(“–n_epochs”, type=int, default=5000, help=“Training epochs.”)<br>
parser.add_argument(“–batch_size”, type=int, default=1, help=“Batch size.”)<br>
parser.add_argument(“–lr”, type=float, default=0.0005, help=“Learning rate.”)<br>
parser.add_argument(“–kld_weight”, type=float, default=1, help=“Weight KLD in loss.”)<br>
parser.add_argument(“–cuda”, type=bool, default=True)<br>
parser.add_argument(<br>
“–num_samples”, type=int, default=1000, help=“Number of samples to generate.”<br>
)</p>
<p>opt = parser.parse_args()</p>
<p>print(“#######”)<br>
print(<br>
“Running experiment %i on %s signals for %i epochs, with KLD weight %f”<br>
% (opt.experiment, opt.signal, opt.n_epochs, opt.kld_weight)<br>
)<br>
print(“######”)</p>
<p>def loss_function(recons, input, mu, log_var, kld_weight=opt.kld_weight):<br>
“”“Computes QVAE loss function.<br>
QVAEloss function is composed of BCE reconstruction loss and weighted KL divergence.<br>
Quaternion-valued KL divergence is defined according to the paper.”“”</p>
<pre><code># recons_loss = F.binary_cross_entropy(recons, input)
recons_loss = F.mse_loss(recons, input)
kld_loss = torch.mean(
    0.5 * (torch.sum(log_var.exp() + mu ** 2 - 1, dim=2))
    - 2 * torch.sum(log_var, dim=2),
    dim=0,
)
kld_loss = torch.mean(kld_loss)

loss = recons_loss + opt.kld_weight * kld_loss
return loss, recons_loss, -kld_loss
</code></pre>
<p>###############################</p>
<h1><a name="p-461498-select-and-setup-experiment-5" class="anchor" href="#p-461498-select-and-setup-experiment-5"></a>Select and setup experiment</h1>
<p>###############################</p>
<h1><a name="p-461498-define-model-6" class="anchor" href="#p-461498-define-model-6"></a>Define model</h1>
<p>qvae = QuaternionFCVAE2(<br>
in_channels=opt.n_channels, latent_dim=opt.latent_dim, n=opt.n<br>
)</p>
<p>if opt.experiment == 1:<br>
# Define input signal<br>
if opt.signal == “proper”:<br>
train_loader, val_loader, _ = QProper_signals1(<br>
opt.len_train, opt.len_val, 100, opt.n<br>
)<br>
elif opt.signal == “improper”:<br>
train_loader, val_loader, _ = QImproper_signals1(<br>
opt.len_train, opt.len_val, 100, opt.n<br>
)<br>
else:<br>
print(“Wrong kind of signal. Signal can be either ‘proper’ or ‘improper’.”)</p>
<p>elif opt.experiment == 2:<br>
# Define input signal<br>
if opt.signal == “proper”:<br>
train_loader, val_loader, _ = QProper_signals2(<br>
opt.len_train, opt.len_val, 100, opt.n<br>
)<br>
elif opt.signal == “improper”:<br>
train_loader, val_loader, _ = QImproper_signals2(<br>
opt.len_train, opt.len_val, 100, opt.n<br>
)<br>
else:<br>
print(“Wrong kind of signal. Signal can be either ‘proper’ or ‘improper’.”)</p>
<p>print(<br>
“Number of parameters”, sum(p.numel() for p in qvae.parameters() if p.requires_grad)<br>
)<br>
device = torch.device(“cuda” if torch.cuda.is_available() and opt.cuda else “cpu”)<br>
qvae.to(device)</p>
<p>optimizer = optim.Adam(qvae.parameters(), lr=opt.lr)<br>
loss_train = <span class="chcklst-box fa fa-square-o fa-fw"></span><br>
loss_val = <span class="chcklst-box fa fa-square-o fa-fw"></span><br>
kld_train = <span class="chcklst-box fa fa-square-o fa-fw"></span><br>
kld_val = <span class="chcklst-box fa fa-square-o fa-fw"></span></p>
<p>device = torch.device(“cpu”)</p>
<p>if opt.cuda:<br>
device = “cuda:%i” % opt.gpu_num<br>
else:<br>
device = “cpu”</p>
<p>###########################</p>
<h1><a name="p-461498-define-and-run-training-7" class="anchor" href="#p-461498-define-and-run-training-7"></a>Define and run training</h1>
<p>###########################</p>
<p>def train(model):<br>
model.train()<br>
start = time.time()<br>
for epoch in range(opt.n_epochs):<br>
# Training<br>
temp_loss_train = <span class="chcklst-box fa fa-square-o fa-fw"></span><br>
temp_kld_train = <span class="chcklst-box fa fa-square-o fa-fw"></span><br>
for idx, data in enumerate(train_loader):<br>
data = data.to(device)<br>
optimizer.zero_grad()<br>
# Apply model<br>
recons, input, mu, log_var = model(data)<br>
# Compute loss function<br>
loss, _, kld = loss_function(recons, input, mu, log_var)<br>
kld_train.append(kld.detach().item())<br>
temp_kld_train.append(kld.detach().item())<br>
loss_train.append(loss.detach().item())<br>
temp_loss_train.append(loss.detach().item())<br>
loss.backward()<br>
optimizer.step()</p>
<pre><code>    # Validation
    with torch.no_grad():
        temp_loss_val = []
        temp_kld_val = []
        for val_data in val_loader:
            val_data = val_data.to(device)
            # Evaluate model
            val_recons, val_input, val_mu, val_log_var = model(val_data)
            # Compute loss function
            loss, _, kld = loss_function(val_recons, val_input, val_mu, val_log_var)
            kld_val.append(kld.detach().item())
            temp_kld_val.append(kld.detach().item())
            temp_loss_val.append(loss.item())
            loss_val.append(loss.item())

            if epoch % 10 == 0:
                if opt.track_signals:
                    gen_samples = model.sample(
                        num_samples=opt.num_samples, current_device=opt.gpu_num
                    )
                    df = pd.DataFrame(gen_samples.detach().cpu().numpy())
                    df.to_csv(
                        "./signals/toy_example%i/track_signals/%s_samples_%i.csv"
                        % (opt.experiment, opt.signal, epoch),
                        index=False, header=None
                    )

    end = time.time()
    print(
        "[Epoch: %i][Train loss: %f][Train KLD: %f][Val loss: %f][Val KLD: %f][Time: %f]"
        % (
            epoch,
            np.mean(temp_loss_train),
            np.mean(temp_kld_train),
            np.mean(temp_loss_val),
            np.mean(temp_kld_val),
            end - start,
        )
    )
#         scheduler.step()

# # Store losses
# torch.save(loss_train, 'checkpoints/toy_example2/loss_train_qproper')
# torch.save(loss_val, 'checkpoints/toy_example2/loss_val_qproper')
# torch.save(kld_train, 'checkpoints/toy_example2/kld_train_qproper')
# torch.save(kld_val, 'checkpoints/toy_example2/kld_val_qproper')

# Store model
torch.save(
    model.state_dict(),
    "./%i/model_%s_epoch%i" % (opt.experiment, opt.signal, epoch),
)
</code></pre>
<p>train(qvae)<br>
"</p>

ptrblck: <p>I guess the conditions checking the signal to create the <code>train_loader</code> might not be met and this object is thus never created. You could error out instead of printing a message only.</p>
<p>Since your code is not properly formatted I’m unable to run and debug it further.</p>