How to create a neural network model in PyTorch?
Creating a neural network model in PyTorch usually involves defining a custom class that inherits from the torch.nn.Module class. Here is a simple example:
import torch
import torch.nn as nn
class SimpleNN(nn.Module):
def __init__(self):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(784, 128) # 定义一个全连接层
self.relu = nn.ReLU() # 定义一个激活函数
self.fc2 = nn.Linear(128, 10) # 定义另一个全连接层
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
In the example above, we have defined a basic neural network model called SimpleNN, which consists of two fully connected layers and a ReLU activation function. The __init__ method is used to define the structure of the model, while the forward method is used to define the forward propagation process of the model.
To use this model, you can instantiate an object and pass in input data for forward propagation calculation.
model = SimpleNN()
input_data = torch.randn(1, 784) # 创建一个输入数据张量
output = model(input_data) # 进行前向传播
print(output)
You can now easily create a simple neural network model in PyTorch. Feel free to define more complex model structures and forward propagation processes based on your needs.