2017-12-27 912 views
0

我试图在我训练它时动态添加隐藏单元到3层神经网络(输入,隐藏,输出)。我想保持网络的一部分受过训练的权重,因为我添加新的隐藏units.This是我的代码,pytorch中隐藏单元的动态添加

class my_network(torch.nn.Module): 
    def __init__(self,input_dim,hidden_dim,output_dim): 
     super(my_network,self).__init__() 
     self.I = input_dim 
     self.H = hidden_dim 
     self.O = output_dim 
     self.layer1 = torch.nn.Linear(input_dim,hidden_dim) 
     self.layer2 = torch.nn.Linear(hidden_dim,output_dim) 

    def add_neurons(self,no_of_neurons,flag): 
     if flag == 1: 
      weights = [self.layer1.weight.data,self.layer2.weight.data] 
      self.layer1 = torch.nn.Linear(self.I,self.H+no_of_neurons) 
      self.layer2 = torch.nn.Linear(self.H+no_of_neurons,self.O) 
      self.layer1.weight.data[0:-no_of_neurons,:] = weights[0] 
      self.layer2.weight.data[:,0:-no_of_neurons] = weights[1] 
      self.H = self.H + no_of_neurons 
     return self.layer1.weight.shape[0] 

    def forward(self,x): 
     temp = self.layer1(x) 
     out = self.layer2(temp) 
     return out 

我注意到,一旦我称之为“add_neurons”的方法,权重停止更新(而梯度被生成)。任何帮助将非常感激。

回答

0

优化器可能不会被通知您添加到模型中的新参数。最简单的可能是使用更新的模型参数列表重新创建优化器对象。