训练神经网络生成500个epoch的acc
时间: 2023-08-01 09:10:24 浏览: 84
好的,训练神经网络可以使用许多深度学习框架,如TensorFlow、PyTorch、Keras等。这里我将提供一个使用PyTorch训练神经网络并记录每个epoch准确率的示例代码。
```
import torch
import torchvision
import torchvision.transforms as transforms
# 定义转换器
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
# 加载训练数据集
trainset = torchvision.datasets.MNIST(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64,
shuffle=True, num_workers=2)
# 定义模型
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = torch.nn.Conv2d(1, 6, 5)
self.pool = torch.nn.MaxPool2d(2, 2)
self.conv2 = torch.nn.Conv2d(6, 16, 5)
self.fc1 = torch.nn.Linear(16 * 4 * 4, 120)
self.fc2 = torch.nn.Linear(120, 84)
self.fc3 = torch.nn.Linear(84, 10)
def forward(self, x):
x = self.pool(torch.nn.functional.relu(self.conv1(x)))
x = self.pool(torch.nn.functional.relu(self.conv2(x)))
x = x.view(-1, 16 * 4 * 4)
x = torch.nn.functional.relu(self.fc1(x))
x = torch.nn.functional.relu(self.fc2(x))
x = self.fc3(x)
return x
# 定义模型、损失函数和优化器
net = Net()
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 训练模型
for epoch in range(500):
running_loss = 0.0
correct = 0
total = 0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
acc = 100 * correct / total
print('Epoch %d, Loss: %.3f, Accuracy: %.3f%%' %
(epoch + 1, running_loss / len(trainloader), acc))
```
在每个epoch的循环中,我们通过计算准确率来记录模型的性能,并在每个epoch结束时打印出来。如果您想将每个epoch的准确率记录到一个文件中,可以使用Python的文件操作来实现。
阅读全文