【问题标题】:Pytorch | I don't know why it is throwing an error? (Beginner)火炬 |不知道为什么会报错? (初学者)
【发布时间】:2020-08-18 14:29:39
【问题描述】:
import torch.nn as nn
import torch.nn.functional as F

## TODO: Define the NN architecture
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # linear layer (784 -> 1 hidden node)
        self.fc1 = nn.Linear(28 * 28, 512)
        self.fc2 = nn.Linear(512 * 512)
        self.fc3 = nn.Linear(512 * 10)

    def forward(self, x):
        # flatten image input
        x = x.view(-1, 28 * 28)
        # add hidden layer, with relu activation function
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = F.relu(self.fc3(x))
        return x

# initialize the NN
model = Net()
print(model)

当我运行它时,它会抛出这个错误。为什么?

TypeError: __ init __() 缺少 1 个必需的位置参数:'out_features'

【问题讨论】:

    标签: pytorch mnist conv-neural-network


    【解决方案1】:

    这个错误是因为你没有在你的 fc2 和 fc3 中提供全连接层的输出大小。 下面是修改后的代码。我添加了输出大小,我不确定这是否是您想要的输出大小架构。但是为了演示,我把输出大小。请根据您的要求编辑代码并添加输出大小。

    记住前一个全连接层的输出大小应该是下一个FC层的输入大小。否则会抛出大小不匹配错误。

    import torch.nn as nn
    import torch.nn.functional as F
    
    ## TODO: Define the NN architecture
    class Net(nn.Module):
        def __init__(self):
            super(Net, self).__init__()
            # linear layer (784 -> 1 hidden node)
            self.fc1 = nn.Linear(28 * 28, 512)
            self.fc2 = nn.Linear(512 ,512*10)
            self.fc3 = nn.Linear(512 * 10,10)
    
        def forward(self, x):
            # flatten image input
            x = x.view(-1, 28 * 28)
            # add hidden layer, with relu activation function
            x = F.relu(self.fc1(x))
            x = F.relu(self.fc2(x))
            x = F.relu(self.fc3(x))
            return x
    
    # initialize the NN
    model = Net()
    print(model)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 2023-03-19
      • 2019-06-18
      相关资源
      最近更新 更多