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」的方法,權重停止更新(而梯度被生成)。任何幫助將非常感激。