gpt4 book ai didi

python - Pytorch教程代码错误: "NameError: name ' net' is not defined"

转载 作者:行者123 更新时间:2023-12-01 23:36:41 28 4
gpt4 key购买 nike

代码来自tutorial for PyTorch .我正在使用 Google Collabs notebook 来运行代码。

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

教程说输出应该是这样的:

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

在我看来,net 已定义,所以我不清楚为什么会发生此错误。我一开始就不是 Python 专家,所以也许我遗漏了一些明显的东西。

最佳答案

您的缩进意味着这些行:

  net = Net()
print(net)

Net 类的一部分,因为它们与类定义在同一范围内。

将它们移到该类定义之外(即,删除这些行的空白缩进)它应该可以工作。

我还建议改用四个空格而不是两个缩进,以使 Python 的空白更易于扫描。

关于python - Pytorch教程代码错误: "NameError: name ' net' is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65494534/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com