【发布时间】:2020-06-20 00:26:09
【问题描述】:
我需要从 pytorch 中经过训练的 NN 中提取权重、偏差和至少激活函数的类型。
我知道提取权重和偏差的命令是:
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)
如果我运行命令
print(model)
我明白了
NetWithODE(
(hidden): Linear(in_features=4, out_features=10, bias=True)
(predict): Linear(in_features=10, out_features=4, bias=True)
)
但是我在哪里可以获得激活函数(在本例中为 Relu)?
我有 pytorch 1.4。
【问题讨论】: