pytorch全连接神经网络搭建
时间: 2023-08-24 08:06:10 浏览: 95
pytorch搭建的全连接神经网络
以下是使用PyTorch搭建全连接神经网络的基本步骤:
1. 导入必要的库
```python
import torch
import torch.nn as nn
import torch.optim as optim
```
2. 定义神经网络模型
这里我们定义一个简单的全连接神经网络,包含3层,每层分别为输入层、隐藏层和输出层:
```python
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(784, 256)
self.fc2 = nn.Linear(256, 128)
self.fc3 = nn.Linear(128, 10)
def forward(self, x):
x = x.view(-1, 784)
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
```
3. 定义损失函数和优化器
```python
model = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
```
4. 加载数据
```python
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False)
```
5. 训练模型
```python
for epoch in range(10):
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 1000 == 999: # 每1000个batch打印一次loss
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 1000))
running_loss = 0.0
```
6. 测试模型
```python
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
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: %d %%' % (100 * correct / total))
```
这样就可以使用PyTorch搭建一个简单的全连接神经网络了。需要注意的是,如果要使用GPU加速训练,可以将模型和数据移动到GPU上,如:
```python
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)
inputs, labels = inputs.to(device), labels.to(device)
```
阅读全文