NameError:未定义名称“ nn”

时间:2019-06-17 14:13:21

标签: pytorch

多次复制PyTorch代码时,出现此错误:

NameError: name 'nn' is not defined

缺少什么?什么是nn


要复制:

class SLL(nn.Module):
    "single linear layer"
    def __init__(self):
        super().__init__()
        self.l1 = nn.Linear(10,100)        

    def forward(self)->None: 
        print("SLL:forward")

m1 = SLL()

1 个答案:

答案 0 :(得分:3)

如果收到此错误,则可以使用以下代码进行修复:

import torch
import torch.nn as nn

您需要同时包含这两行,因为如果仅设置第二行,那么如果未导入torch程序包,则可能行不通。

其中两个主要PyTorch软件包分别位于torchtorch.nn(或仅nn)中。您可以help(torch.nn)进行确认。

包含nn并将功能接口包含为F的情况并不少见:

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

为了给您一些提示,您提供了导入的列表或nn包中的内容:

['AdaptiveAvgPool1d', 'AdaptiveAvgPool2d', 'AdaptiveAvgPool3d', 'AdaptiveLogSoftmaxWithLoss', 'AdaptiveMaxPool1d', 'AdaptiveMaxPool2d', 'AdaptiveMaxPool3d', 'AlphaDropout', 'AvgPool1d', 'AvgPool2d', 'AvgPool3d', 'BCELoss', 'BCEWithLogitsLoss', 'BatchNorm1d', 'BatchNorm2d', 'BatchNorm3d', 'Bilinear', 'CELU', 'CTCLoss', 'ConstantPad1d', 'ConstantPad2d', 'ConstantPad3d', 'Container', 'Conv1d', 'Conv2d', 'Conv3d', 'ConvTranspose1d', 'ConvTranspose2d', 'ConvTranspose3d', 'CosineEmbeddingLoss', 'CosineSimilarity', 'CrossEntropyLoss', 'CrossMapLRN2d', 'DataParallel', 'Dropout', 'Dropout2d', 'Dropout3d', 'ELU', 'Embedding', 'EmbeddingBag', 'FeatureAlphaDropout', 'Fold', 'FractionalMaxPool2d', 'GLU', 'GRU', 'GRUCell', 'GroupNorm', 'Hardshrink', 'Hardtanh', 'HingeEmbeddingLoss', 'InstanceNorm1d', 'InstanceNorm2d', 'InstanceNorm3d', 'KLDivLoss', 'L1Loss', 'LPPool1d', 'LPPool2d', 'LSTM', 'LSTMCell', 'LayerNorm', 'LeakyReLU', 'Linear', 'LocalResponseNorm', 'LogSigmoid', 'LogSoftmax', 'MSELoss', 'MarginRankingLoss', 'MaxPool1d', 'MaxPool2d', 'MaxPool3d', 'MaxUnpool1d', 'MaxUnpool2d', 'MaxUnpool3d', 'Module', 'ModuleDict', 'ModuleList', 'MultiLabelMarginLoss', 'MultiLabelSoftMarginLoss', 'MultiMarginLoss', 'NLLLoss', 'NLLLoss2d', 'PReLU', 'PairwiseDistance', 'Parameter', 'ParameterDict', 'ParameterList', 'PixelShuffle', 'PoissonNLLLoss', 'RNN', 'RNNBase', 'RNNCell', 'RNNCellBase', 'RReLU', 'ReLU', 'ReLU6', 'ReflectionPad1d', 'ReflectionPad2d', 'ReplicationPad1d', 'ReplicationPad2d', 'ReplicationPad3d', 'SELU', 'Sequential', 'Sigmoid', 'SmoothL1Loss', 'SoftMarginLoss', 'Softmax', 'Softmax2d', 'Softmin', 'Softplus', 'Softshrink', 'Softsign', 'Tanh', 'Tanhshrink', 'Threshold', 'TripletMarginLoss', 'Unfold', 'Upsample', 'UpsamplingBilinear2d', 'UpsamplingNearest2d', 'ZeroPad2d', '_VF', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_functions', '_reduction', 'backends', 'functional', 'grad', 'init', 'modules', 'parallel', 'parameter', 'utils']

包含许多可能最基本的类是PyTorch类nn.Module

不要将PyTorch类nn.Module与Python模块混淆。


要从问题中修复SSL模型,只需添加前两行:

import torch
import torch.nn as nn

class SLL(nn.Module):
    "single linear layer"
    def __init__(self):
        super().__init__()
        self.l1 = nn.Linear(10,100)        

    def forward(self)->None: 
        print("SLL:forward")

# we create a module instance m1
m1 = SLL()

您将获得输出:

SLL(
  (l1): Linear(in_features=10, out_features=100, bias=True)
)