使用pytorch重写上面的代码
时间: 2023-09-22 14:06:38 浏览: 68
好的,下面是使用PyTorch库重写的手写数字识别代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
# 定义数据预处理
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
# 下载并导入MNIST数据集
train_dataset = datasets.MNIST(root='./data/', train=True, transform=transform, download=True)
test_dataset = datasets.MNIST(root='./data/', train=False, transform=transform, download=True)
# 定义数据加载器
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=100, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=100, shuffle=False)
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc = nn.Linear(784, 10)
def forward(self, x):
x = x.view(-1, 784)
x = self.fc(x)
return torch.nn.functional.softmax(x, dim=1)
# 创建模型和优化器
net = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)
# 开始训练模型
for epoch in range(25):
avg_loss = 0.
for i, (images, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = net(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
avg_loss += loss.item() / len(train_loader)
print("Epoch:", '%04d' % (epoch+1), "loss=", "{:.9f}".format(avg_loss))
print("Optimization Finished!")
# 测试模型
correct = 0
total = 0
with torch.no_grad():
for images, labels in test_loader:
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy: %.2f %%' % (100 * correct / total))
```
这段代码使用了PyTorch的自动求导和数据加载器等功能,与TensorFlow的代码相比更加简洁和易于理解。
阅读全文