How to create a neural network model in PyTorch

Creating a neural network model in PyTorch mainly involves defining a class that inherits from nn.Module and implementing the __init__ and forward methods.

Here is a simple example showcasing how to create a neural network model with a fully connected layer.

import torch
import torch.nn as nn

class SimpleNet(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(SimpleNet, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.fc2 = nn.Linear(hidden_size, output_size)
    
    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

# 创建一个SimpleNet实例
model = SimpleNet(input_size=10, hidden_size=20, output_size=1)

In the above example, we initially define a class SimpleNet, which inherits from nn.Module, and we define two fully connected layers in the __init__ method. In the forward method, we define the forward propagation process of the model. Finally, we create an instance of SimpleNet as our neural network model.

bannerAds