如何在PyTorch中定义一个简单的卷积神经网络?


要定义一个简单的卷积神经网络(ANN),我们可以使用以下步骤:

步骤

  • 首先,我们导入重要的库和包。我们尝试在PyTorch中实现一个简单的ANN。在以下所有示例中,所需的Python库是**torch**。确保您已安装它。

import torch import torch.nn as nn
  • 我们的下一步是构建一个简单的ANN模型。在这里,我们使用nn包来实现我们的模型。为此,我们定义一个类**MyNetwork**并将**nn.Module**作为参数传递。

class MyNetwork(nn.Module):
  • 我们需要在类中创建两个函数来准备我们的模型。第一个是init(),第二个是**forward()**。在**init()**函数中,我们调用**super()**函数并定义不同的层。

  • 我们需要实例化该类才能用于数据集上的训练。当我们实例化该类时,将执行**forward()**函数。

model = MyNetwork()
  • 打印**model**以查看不同的层。

print(model)

示例1

在下面的示例中,我们创建了一个简单的具有四层的人工神经网络,没有前向函数。

# Import the required libraries import torch from torch import nn # define a simple sequential model model = nn.Sequential( nn.Linear(32, 128), nn.ReLU(), nn.Linear(128, 10), nn.Sigmoid() ) # print the model print(model)

输出

Sequential(
   (0): Linear(in_features=32, out_features=128, bias=True)
   (1): ReLU()
   (2): Linear(in_features=128, out_features=10, bias=True)
   (3): Sigmoid()
)

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例2

下面的Python程序展示了构建简单神经网络的不同方法。

import torch import torch.nn as nn import torch.nn.functional as F class MyNet(nn.Module): def __init__(self): super(MyNet, self).__init__() self.fc1 = nn.Linear(4, 8) self.fc2 = nn.Linear(8, 16) self.fc3 = nn.Linear(16, 4) self.fc4 = nn.Linear(4,1) def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) return torch.sigmoid(self.fc4(x)) model = MyNet() print(model)

输出

MyNet(
   (fc1): Linear(in_features=4, out_features=8, bias=True)
   (fc2): Linear(in_features=8, out_features=16, bias=True)
   (fc3): Linear(in_features=16, out_features=4, bias=True)
   (fc4): Linear(in_features=4, out_features=1, bias=True)
)

更新于:2022年1月25日

467 次浏览

开启您的职业生涯

通过完成课程获得认证

开始学习
广告