我需要从 pytorch 中经过训练的神经网络中提取权重、偏差和至少激活函数的类型。
我知道要提取权重和偏差,命令是:
model.parameters()
但我不知道如何提取层上使用的激活函数。这是我的网络
class NetWithODE(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output, sampling_interval, scaler_features):
super(NetWithODE, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer
self.predict = torch.nn.Linear(n_hidden, n_output) # output layer
self.sampling_interval = sampling_interval
self.device = torch.device("cpu")
self.dtype = torch.float
self.scaler_features = scaler_features
def forward(self, x):
x0 = x.clone().requires_grad_(True)
# activation function for hidden layer
x = F.relu(self.hidden(x))
# linear output, here r should be the output
r = self.predict(x)
# Now the r enters the integrator
x = self.integrate(r, x0)
return x
def integrate(self, r, x0):
# RK4 steps per interval
M = 4
DT = self.sampling_interval / M
X = x0
for j in range(M):
k1 = self.ode(X, r)
k2 = self.ode(X + DT / 2 * k1, r)
k3 = self.ode(X + DT / 2 * k2, r)
k4 = self.ode(X + DT * k3, r)
X = X + DT / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
return X
def ode(self, x0, r):
qF = r[0, 0]
qA = r[0, 1]
qP = r[0, 2]
mu = r[0, 3]
FRU = x0[0, 0]
AMC = x0[0, 1]
PHB = x0[0, 2]
TBM = x0[0, 3]
fFRU = qF * TBM
fAMC = qA * TBM
fPHB = qP - mu * PHB
fTBM = mu * TBM
return torch.stack((fFRU, fAMC, fPHB, fTBM), 0)
Run Code Online (Sandbox Code Playgroud)
如果我运行命令
print(model)
Run Code Online (Sandbox Code Playgroud)
我明白了
NetWithODE(
(hidden): Linear(in_features=4, out_features=10, bias=True)
(predict): Linear(in_features=10, out_features=4, bias=True)
)
Run Code Online (Sandbox Code Playgroud)
但是我在哪里可以获得激活函数(在本例中为 Relu)?
我有pytorch 1.4。
有两种向网络图添加操作的方法:低级函数方法和更高级的对象方法。您需要后者使您的结构可观察,在第一种情况下只是调用(不完全是,但是......)一个函数而不存储有关它的信息。所以,而不是
def forward(self, x):
...
x = F.relu(self.hidden(x))
Run Code Online (Sandbox Code Playgroud)
它一定是类似的东西
def __init__(...):
...
self.myFirstRelu= torch.nn.ReLU()
def forward(self, x):
...
x1 = self.hidden(x)
x2 = self.myFirstRelu(x1)
Run Code Online (Sandbox Code Playgroud)
无论如何,混合使用这两种方法通常是个坏主意,尽管即使torchvision模型也存在这样的不一致:models.inception_v3例如不注册池>:-((编辑:它已于 2020 年 6 月修复,谢谢,mitmul!)。
UPD: - Thanks, that works, now if I print I see ReLU(). But this seems to only print the function in the same order they are defined in the init. Is there a way to get the associations between layers and activation functions? For example I want to know which activation was applyed to layer 1, which to layer 2 end so on...
There is no uniform way, but here is some tricks: object way:
-just init them in order
-use torch.nn.Sequential
-hook callbacks on nodes like that -
def hook( m, i, o):
print( m._get_name() )
for ( mo ) in model.modules():
mo.register_forward_hook(hook)
Run Code Online (Sandbox Code Playgroud)
functional and object way:
-make use of internal model graph, builded on forward pass, as torchviz do (https://github.com/szagoruyko/pytorchviz/blob/master/torchviz/dot.py), or just use plot generated by said torchviz.