2017-05-08 137 views
0

我想新的节点添加到输出层以后训练它,我是这样做的:添加到输出层新节点Keras

def add_outputs(self, n_new_outputs): 
    out = self.model.get_layer('fc8').output 
    last_layer = self.model.get_layer('fc7').output 
    out2 = Dense(n_new_outputs, activation='softmax', name='fc9')(last_layer) 
    output = merge([out, out2], mode='concat') 
    self.model = Model(input=self.model.input, output=output) 

其中'fc7'是完全连接层输出层'fc8'前。我执行最后一层out = self.model.get_layer('fc8').output,但输出是所有模型。 有没有什么办法只从网络上取一层? 也许那里有其他更简单的方式来做到这一点....

谢谢!!!!

回答

0

最后我找到一个解决方案:

1)从最后一层

2得到的权重)加零,以权重和随机初始化的连接

3)弹出输出层和创建一个新的

4)设置新权重应用到新的层

此处的代码:

def add_outputs(self, n_new_outputs): 
     #Increment the number of outputs 
     self.n_outputs += n_new_outputs 
     weights = self.model.get_layer('fc8').get_weights() 
     #Adding new weights, weights will be 0 and the connections random 
     shape = weights[0].shape[0] 
     weights[1] = np.concatenate((weights[1], np.zeros(n_new_outputs)), axis=0) 
     weights[0] = np.concatenate((weights[0], -0.0001 * np.random.random_sample((shape, n_new_outputs)) + 0.0001), axis=1) 
     #Deleting the old output layer 
     self.model.layers.pop() 
     last_layer = self.model.get_layer('batchnormalization_1').output 
     #New output layer 
     out = Dense(self.n_outputs, activation='softmax', name='fc8')(last_layer) 
     self.model = Model(input=self.model.input, output=out) 
     #set weights to the layer 
     self.model.get_layer('fc8').set_weights(weights) 
     print(weights[0])