用pytorch实现一个神经网络,输入维度随意,隐藏层的输出通道数分别为32和64,输出层的输出维度为128,要求在输出层之前需要使用dropout,dropout=0.3
时间: 2024-05-05 12:19:17 浏览: 6
好的,你可以使用下面的代码实现这个神经网络:
```
import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self, in_dim, hidden_dim_1, hidden_dim_2, out_dim, dropout_rate):
super(Net, self).__init__()
self.hidden1 = nn.Linear(in_dim, hidden_dim_1)
self.hidden2 = nn.Linear(hidden_dim_1, hidden_dim_2)
self.drop = nn.Dropout(p=dropout_rate)
self.out = nn.Linear(hidden_dim_2, out_dim)
def forward(self, x):
x = self.hidden1(x)
x = torch.relu(x)
x = self.hidden2(x)
x = torch.relu(x)
x = self.drop(x)
x = self.out(x)
return x
# Example usage
net = Net(20, 32, 64, 128, 0.3)
input_tensor = torch.randn(1, 20)
output_tensor = net(input_tensor)
print(output_tensor.size())
```
这个神经网络使用了两个线性层作为隐藏层,分别输出32和64个通道。在这两个线性层之间使用了ReLU激活函数。在第二个隐藏层之后使用了dropout,它的概率为0.3。最后使用了一个线性层作为输出层,输出维度为128。