全连接层加dropout代码pytorch
时间: 2023-09-17 12:07:51 浏览: 103
全连接神经网络-pytorch
以下是全连接层加dropout的PyTorch代码:
```python
import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(784, 512)
self.dropout1 = nn.Dropout(p=0.5)
self.fc2 = nn.Linear(512, 256)
self.dropout2 = nn.Dropout(p=0.5)
self.output = nn.Linear(256, 10)
def forward(self, x):
x = x.view(-1, 784)
x = self.fc1(x)
x = nn.functional.relu(x)
x = self.dropout1(x)
x = self.fc2(x)
x = nn.functional.relu(x)
x = self.dropout2(x)
x = self.output(x)
return x
```
在上面的代码中,我们创建一个包含两个全连接层和两个dropout层的神经网络。dropout层的概率为0.5,这意味着每个输入元素有0.5的概率被随机清除。这有助于防止过拟合,提高训练的泛化能力。
阅读全文