基于pytorch的MLP
时间: 2023-12-11 12:32:05 浏览: 101
以下是基于Pytorch的MLP实现的步骤:
1.导入必要的库和模块
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
```
2.定义超参数
```python
input_size = 784 # 输入层大小
hidden_size = 500 # 隐藏层大小
num_classes = 10 # 输出层大小
num_epochs = 10 # 训练轮数
batch_size = 100 # 批处理大小
learning_rate = 0.001 # 学习率
```
3.加载数据集并进行预处理
```python
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='./data', train=True, transform=transform, download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=transform)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
```
4.定义MLP模型
```python
class MLP(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(MLP, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
model = MLP(input_size, hidden_size, num_classes)
```
5.定义损失函数和优化器
```python
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
```
6.训练模型
```python
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.reshape(-1, 28*28)
outputs = model(images)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
```
7.测试模型
```python
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images = images.reshape(-1, 28*28)
outputs = model(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: {} %'.format(100 * correct / total))
```
8.保存模型
```python
torch.save(model.state_dict(), 'mlp.ckpt')
```
阅读全文