使用pycharm实现一个全连接网络的版本;满足 CIFAR-10 分类任务;训 练数据和测试数据为其自带的 50000 和 10000 条。
时间: 2024-04-30 13:19:45 浏览: 65
好的,我们可以使用PyTorch来实现一个全连接网络,满足CIFAR-10分类任务。下面是代码实现:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
# 定义全连接网络
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(32*32*3, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, 10)
def forward(self, x):
x = x.view(-1, 32*32*3)
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# 加载数据集
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64,
shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64,
shuffle=False, num_workers=2)
# 初始化网络和优化器
net = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 训练网络
for epoch in range(10): # 训练 10 个 epoch
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 打印统计信息
running_loss += loss.item()
if i % 200 == 199: # 每 200 个 mini-batch 打印一次统计信息
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 200))
running_loss = 0.0
print('Finished Training')
# 测试网络
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
```
这里我们定义了一个3层的全连接神经网络,输入层有32*32*3=3072个节点,第一隐藏层有512个节点,第二隐藏层有256个节点,输出层有10个节点(对应CIFAR-10数据集的10个类别)。我们使用了交叉熵损失函数和随机梯度下降优化器来训练网络。在训练过程中,我们打印了每 200 个 mini-batch 的平均损失,并进行了 10 个 epoch 的训练。最后,我们测试了网络的准确率,得到了大约 50% 的准确率(这个结果可以通过调整网络结构和训练参数来提升)。
阅读全文