[英]Pytorch tutorial code error: “NameError: name 'net' is not defined”
該代碼來自PyTorch 的教程。 我正在使用 Google Collabs 筆記本來運行代碼。
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())
錯誤是:
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
該教程說 output 應該是這樣的:
10
torch.Size([6, 1, 3, 3])
在我看來, net
已定義,因此我不清楚為什么會發生此錯誤。 首先,我不是 Python 方面的專家,所以我可能缺少一些明顯的東西。
您的縮進意味着這些行:
net = Net()
print(net)
是Net
class 的一部分,因為它們與 class 定義位於相同的 scope 中。
將它們移到 class 定義之外(即,刪除這些行的空白縮進),它應該可以工作。
我還建議使用四個空格而不是兩個空格的縮進,以使 Python 的空格更易於掃描。
您需要在Net
類之外編寫以下語句-
net = Net()
print(net)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.