把你上述写的代码,整合成一个py文件的代码
时间: 2024-02-25 16:59:16 浏览: 115
代码文件.py
好的,以下是整合后的代码:
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.transforms as transforms
from torchvision.datasets import MNIST
# 定义数据转换
transform = transforms.Compose([
transforms.ToTensor(), # 将图像转换为PyTorch张量
transforms.Normalize((0.1307,), (0.3081,)) # 对张量进行标准化
])
# 下载和加载MNIST数据集
train_dataset = MNIST(root='./data', train=True, transform=transform, download=True)
test_dataset = MNIST(root='./data', train=False, transform=transform, download=True)
# 创建数据加载器
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1) # 输入通道数为1,输出通道数为32,卷积核大小为3*3,步长为1
self.conv2 = nn.Conv2d(32, 64, 3, 1) # 输入通道数为32,输出通道数为64,卷积核大小为3*3,步长为1
self.dropout1 = nn.Dropout2d(0.25) # Dropout层,丢弃概率为0.25
self.dropout2 = nn.Dropout2d(0.5) # Dropout层,丢弃概率为0.5
self.fc1 = nn.Linear(9216, 128) # 全连接层,输入大小为9216,输出大小为128
self.fc2 = nn.Linear(128, 10) # 全连接层,输入大小为128,输出大小为10
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
# 定义超参数
learning_rate = 0.001
momentum = 0.9
epochs = 10
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
net = Net()
optimizer = optim.SGD(net.parameters(), lr=learning_rate, momentum=momentum)
# 网络训练
for epoch in range(epochs):
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99:
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 100))
running_loss = 0.0
# 网络性能测试
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
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))
```
阅读全文