假设我有一个名为m. 现在我没有关于这个网络层数的先验信息。如何创建一个 for 循环来遍历其层?我正在寻找类似的东西:
Weight=[]
for layer in m._modules:
Weight.append(layer.weight)
Run Code Online (Sandbox Code Playgroud) python machine-learning neural-network deep-learning pytorch
这应该是一个快速的.当我在PyTorch中使用预定义模块时,我通常可以非常轻松地访问其权重.但是,如果我先将模块包装在nn.Sequential()中,如何访问它们?请看下面的玩具示例
class My_Model_1(nn.Module):
def __init__(self,D_in,D_out):
super(My_Model_1, self).__init__()
self.layer = nn.Linear(D_in,D_out)
def forward(self,x):
out = self.layer(x)
return out
class My_Model_2(nn.Module):
def __init__(self,D_in,D_out):
super(My_Model_2, self).__init__()
self.layer = nn.Sequential(nn.Linear(D_in,D_out))
def forward(self,x):
out = self.layer(x)
return out
model_1 = My_Model_1(10,10)
print(model_1.layer.weight)
model_2 = My_Model_2(10,10)
# How do I print the weights now?
# model_2.layer.0.weight doesn't work.
Run Code Online (Sandbox Code Playgroud)