在pytorch 框架下加载MNIST手写数字数据集,并构建只有一个全连接层和softmax层的网络来进行训练,损失函数为MAE,优化器为SGD
时间: 2024-03-04 16:48:49 浏览: 80
好的,以下是代码实现:
```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,))
])
train_set = datasets.MNIST('./data', train=True, download=True, transform=transform)
test_set = datasets.MNIST('./data', train=False, download=True, transform=transform)
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc = nn.Linear(784, 10) # 全连接层
self.softmax = nn.Softmax(dim=1) # softmax层
def forward(self, x):
x = x.view(-1, 784)
x = self.fc(x)
x = self.softmax(x)
return x
model = Net()
# 定义损失函数和优化器
criterion = nn.L1Loss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)
# 开始训练
for epoch in range(10):
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
print('Train Epoch: {} \t Loss: {:.6f}'.format(epoch+1, loss.item()))
# 测试模型
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
output = model(data)
test_loss += criterion(output, target).item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
```
其中,我们定义了一个名为 `Net` 的类来构建模型,包含一个全连接层和一个 softmax 层,使用 L1 损失函数和 SGD 优化器进行训练,最终输出测试集的平均损失和准确率。
阅读全文