下面我用由浅入深的方式,给你讲 如何用 PyTorch 建模型,从最基础的写法到常见结构,适合初学者到进阶。
在 PyTorch 中,建模型通常有两种方式:
nn.Module(最常用、最推荐)nn.Sequential(简单模型)import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super(MyModel, 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
model = MyModel()
x = torch.randn(32, 784) # batch_size=32
output = model(x)
print(output.shape) # [32, 10]
✅ 核心点
__init__:定义层forward:定义前向传播model = nn.Sequential(
nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 10)
)
x = torch.randn(32, 784)
output = model(x)
✅ 优点:代码少
❌ 缺点:不灵活(不适合复杂结构)
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(1, 16, 3, 1, 1),
nn.ReLU(),
nn.MaxPool2d(2)
)
self.fc = nn.Linear(16 * 14 * 14, 10)
def forward(self, x):
x = self.conv(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
class RNNModel(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(RNNModel, self).__init__()
self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out, _ = self.lstm(x)
out = self.fc(out[:, -1, :])
return out
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
for epoch in range(10):
for x, y in dataloader:
optimizer.zero_grad()
out = model(x)
loss = criterion(out, y)
loss.backward()
optimizer.step()
torch.save(model.state_dict(), "model.pth")
model = MyModel()
model.load_state_dict(torch.load("model.pth"))
model.eval()
nn.Module ✅DataLoadermodel.cuda())如果你愿意,我可以:
你现在是 刚入门 还是 已有基础?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。