如何使用PyTorch库构建一个基础的MNIST手写数字分类器?
时间: 2024-12-15 19:14:37 浏览: 1
要使用PyTorch库构建一个基础的MNIST手写数字分类器,你可以按照以下几个步骤操作:
1. **导入所需库**:
```python
import torch
import torchvision
from torchvision import datasets, transforms
```
2. **数据预处理**:
```python
transform = transforms.Compose([
transforms.ToTensor(), # 将图像转换为张量
transforms.Normalize((0.5,), (0.5,)) # 归一化到0-1之间
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
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)
```
3. **定义模型**:
```python
model = torch.nn.Sequential(
torch.nn.Linear(784, 128), # 输入层到隐藏层
torch.nn.ReLU(), # 非线性激活函数
torch.nn.Linear(128, 10), # 隐藏层到输出层
torch.nn.LogSoftmax(dim=1) # 输出层应用softmax用于概率预测
)
```
4. **损失函数和优化器**:
```python
criterion = torch.nn.NLLLoss() # 交叉熵损失函数
optimizer = torch.optim.SGD(model.parameters(), lr=0.001) # 使用随机梯度下降优化器
```
5. **训练模型**:
```python
num_epochs = 10
for epoch in range(num_epochs):
for images, labels in train_loader:
optimizer.zero_grad() # 梯度清零
outputs = model(images.view(-1, 784))
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {loss.item():.4f}")
```
6. **评估模型**:
```python
with torch.no_grad():
total_correct = 0
for images, labels in test_loader:
outputs = model(images.view(-1, 784))
_, predicted = torch.max(outputs.data, 1)
total_correct += (predicted == labels).sum().item()
accuracy = total_correct / len(test_dataset)
print(f"Test Accuracy: {accuracy * 100:.2f}%")
```
阅读全文