ディープラーニング - ニューラル ネットワークを構築する 2 つの方法

方法 1: ニューラル ネットワーク クラスを定義してインスタンス化する

コード:

import torch
import torch.nn.functional as F


"""
    方法一:定义神经网络类,然后再实例化
"""
# 神经网络类
class Net(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_output):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden)   # hidden layer
        self.predict = torch.nn.Linear(n_hidden, n_output)   # output layer

    def forward(self, x):
        x = F.relu(self.hidden(x))      # activation function for hidden layer
        x = self.predict(x)             # linear output
        return x


# 实例化
net1 = Net(1, 10, 1)
# 输出网络结构
print(net1)

操作結果:

ここに画像の説明を挿入

方法 2: Sequential を使用して迅速にビルドする

コード:

import torch
import torch.nn.functional as F

# 使用Sequential快速搭建
net2 = torch.nn.Sequential(
    torch.nn.Linear(1, 10),
    torch.nn.ReLU(),
    torch.nn.Linear(10, 1)
)


print(net2)     # net2 architecture

操作結果:

ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/Elon15/article/details/131644184