2

The code comes from a tutorial for PyTorch. I'm using Google Collabs notebook to run the code.

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):

  def __init__(self):
    super(Net, self).__init__()
    self.conv1 = nn.Conv2d(1, 6, 3)
    self.conv2 = nn.Conv2d(6, 16, 3)
    self.fc1 = nn.Linear(16 * 6 * 6, 120)
    self.fc2 = nn.Linear(120, 84)
    self.fc3 = nn.Linear(84, 10)

  def forward(self, x):
    x = F.max_pool2d(F.relu(self.conv1(x)), (2,2))
    x = F.max_pool2d(F.relu(self.conv2(x)), 2)
    x = x.view(-1, self.num_flat_features(x))
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)
    return x
  
  def num_flat_features(self, x):
    size = x.size()[1:]
    num_features = 1
    for s in size:
      num_features *= s
    return num_features
  
  net = Net()
  print(net)

# The code works up until here. It's the following chunk that returns an error. 
params = list(net.parameters())
print(len(params))
print(params[0].size())

The error is:

NameError                                 Traceback (most recent call last)

<ipython-input-17-ad79a1eff4f3> in <module>()
     32   print(net)
     33 
---> 34 params = list(net.parameters())
     35 print(len(params))
     36 print(params[0].size())

NameError: name 'net' is not defined

The tutorial says the output should be this instead:

10
torch.Size([6, 1, 3, 3])

It looks to me like net is defined, so I'm unclear why this error is happening. I'm not expert with Python to begin with, so maybe there is something obvious I'm missing.

3
  • 2
    There are indented lines, that shouldn't be. "net" is never created in your code. Commented Dec 29, 2020 at 15:28
  • 2
    It is defined inside of your class. Fix the indents Commented Dec 29, 2020 at 15:28
  • 1
    Remove indents for net = Net(). You are defining it inside a class. It's a local variable to that class Commented Dec 29, 2020 at 15:30

2 Answers 2

4

Your indentation implies that these lines:

  net = Net()
  print(net)

are part of the Net class because they are in the same scope as the class definition.

Move them outside of that class definition (ie, remove the whitespace indentation for those lines) and it should work.

I'd also suggest moving to indentations with four spaces, not two, to make Python's whitespace easier to scan.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the suggestion about the indentation.
2

You need to write the following statements outside Net class-

net = Net()
print(net)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.