torch.nn.Module
是 PyTorch 中神经网络模型的基类,它提供了模型定义、参数管理和其他相关功能。
以下是关于 torch.nn.Module 的详细说明:
torch.nn.Module
是 PyTorch 中所有神经网络模型的基类,它提供了模型定义和许多实用方法。自定义的神经网络模型应该继承自 torch.nn.Module。
import torch
import torch.nn as nn
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Linear(10, 5)
self.relu = nn.ReLU()
def forward(self, x):
x = self.fc(x)
x = self.relu(x)
return x
# 创建模型实例
model = SimpleModel()
import torch
import torch.nn as nn
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=3, stride=1, padding=1)
self.relu = nn.ReLU()
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1)
self.fc = nn.Linear(32 * 7 * 7, 10)
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.pool(x)
x = self.conv2(x)
x = self.relu(x)
x = self.pool(x)
x = x.view(-1, 32 * 7 * 7)
x = self.fc(x)
return x
# 创建CNN模型实例
cnn_model = CNN()
import torch
import torch.nn as nn
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h0 = torch.zeros(1, x.size(0), self.hidden_size)
out, _ = self.rnn(x, h0)
out = self.fc(out[:, -1, :])
return out
# 创建RNN模型实例
rnn_model = RNN(input_size=10, hidden_size=20, output_size=5)
这些示例展示了使用 torch.nn.Module 来构建不同类型的神经网络模型。