我正在尝试创建具有 N 层的前馈神经网络 所以想法是假设如果我想要 2 个输入、3 个隐藏和 2 个输出,那么我只需将 [2,3,2] 传递给神经网络类,并且神经网络模型将被创建,所以如果我想要 [100,1000,1000,2] 在这种情况下,100 个是输入,两个隐藏层各包含 1000 个神经元和 2 个输出,所以我想要完全连接的神经网络,我只想传递包含每层神经元数量的列表。 为此我编写了以下代码
class FeedforwardNeuralNetModel(nn.Module):
def __init__(self, layers):
super(FeedforwardNeuralNetModel, self).__init__()
self.fc=[]
self.sigmoid=[]
self.activationValue = []
self.layers = layers
for i in range(len(layers)-1):
self.fc.append(nn.Linear(layers[i],layers[i+1]))
self.sigmoid.append(nn.Sigmoid())
def forward(self, x):
out=x
for i in range(len(self.fc)):
out=self.fc[i](out)
out = self.sigmoid[i](out)
return out
当我尝试使用它时,我发现它是一种空模型
model=FeedforwardNeuralNetModel([3,5,10,2])
print(model)
>>FeedforwardNeuralNetModel()
当我使用以下代码时
class FeedforwardNeuralNetModel(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(FeedforwardNeuralNetModel, self).__init__()
# Linear function
self.fc1 = nn.Linear(input_dim, hidden_dim)
# Non-linearity
self.tanh = nn.Tanh()
# Linear function (readout)
self.fc2 = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
# Linear function
out = self.fc1(x)
# Non-linearity
out = self.tanh(out)
# Linear function (readout)
out = self.fc2(out)
return out
当我尝试打印这个模型时,我发现了以下结果
print(model)
>>FeedforwardNeuralNetModel(
(fc1): Linear(in_features=3, out_features=5, bias=True)
(sigmoid): Sigmoid()
(fc2): Linear(in_features=5, out_features=10, bias=True)
)
在我的代码中,我只是创建列表,这就是区别 我只是想了解为什么在 torch 列表模型组件中没有用?
最佳答案
如果您执行print(FeedForwardNetModel([1,2,3])
,则会出现以下错误
AttributeError:“FeedforwardNeuralNetModel”对象没有属性“_modules”
这基本上意味着该对象无法识别您声明的模块。
为什么会发生这种情况?
目前,模块是在 self.fc
中声明的,它是 list
,因此 torch 无法知道它是否是一个模型,除非它进行了深入的操作。搜索
是糟糕且低效的。
我们如何让torch知道self.fc
是一个模块列表?
通过使用nn.ModuleList
(请参阅下面的修改代码)。 ModuleList和ModuleDict分别是python列表和字典,但它们告诉torch list/dict包含一个nn模块。
#modified init function
def __init__(self, layers):
super().__init__()
self.fc=nn.ModuleList()
self.sigmoid=[]
self.activationValue = []
self.layers = layers
for i in range(len(layers)-1):
self.fc.append(nn.Linear(layers[i],layers[i+1]))
self.sigmoid.append(nn.Sigmoid())
关于python - 为什么在 pyTorch 中列出模型组件没有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54143427/