给我一个神经网络搭建的例子,详细实操
时间: 2024-02-25 17:53:10 浏览: 54
好的,以下是一个简单的神经网络搭建的例子,详细实操。
我们将使用Python和PyTorch来搭建一个简单的全连接神经网络,用于对手写数字进行分类。
首先,我们需要导入必要的库:
``` python
import torch
import torch.nn as nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
```
接下来,我们需要加载数据集。这里我们使用MNIST数据集:
``` python
train_dataset = dsets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = dsets.MNIST(root='./data', train=False, transform=transforms.ToTensor())
```
然后,我们定义一些超参数:
``` python
input_size = 784
hidden_size = 500
num_classes = 10
num_epochs = 5
batch_size = 100
learning_rate = 0.001
```
接着,我们定义一个自定义的神经网络类:
``` python
class Net(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(Net, 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
net = Net(input_size, hidden_size, num_classes)
```
然后,我们定义损失函数和优化器:
``` python
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)
```
接下来,我们开始训练:
``` python
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.reshape(-1, 28*28)
outputs = net(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, len(train_dataset)//batch_size, loss.item()))
```
最后,我们在测试集上进行测试:
``` python
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images = images.reshape(-1, 28*28)
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: {} %'.format(100 * correct / total))
```
这就是一个简单的神经网络搭建的例子。
阅读全文