pytorch搭建分类网络
时间: 2023-11-18 13:02:40 浏览: 80
PyTorch是一个基于Python的科学计算库,它是一个用于构建深度学习模型的框架,提供了丰富的API和工具,方便用户进行模型训练和推理。下面是一个简单的PyTorch搭建分类网络的示例代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
# Define the neural network architecture
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# Create the neural network instance
net = Net()
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# Train the neural network
for epoch in range(10): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
if i % 2000 == 1999: # print every 2000 mini-batches
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
```
在上述代码中,我们定义了一个名为`Net`的类,该类继承自`nn.Module`,并且包含了卷积层、池化层和全连接层。我们还定义了损失函数和优化器,并在训练时使用了它们。在训练过程中,我们使用`enumerate()`函数遍历了训练集,并在每个迭代中计算了模型的输出和损失,并使用反向传播优化模型的参数。最后,我们训练了10个epoch,并打印了训练过程中的损失。
请注意,这只是一个简单的示例,实际应用中的神经网络可能会更加复杂,并且需要根据具体问题进行调整。
阅读全文