问题描述
我正在做一个项目,该项目需要我向神经网络的输出层添加新的单元以实现某种形式的迁移学习.我想知道是否可以使用Keras或TensorFlow设置单位的权重.
I am working on a project that requires me to add new units to the output layer of a neural network to implement a form of transfer learning. I was wondering if I could do this and set the units' weights using either Keras or TensorFlow.
具体来说,我想将输出神经元附加到Keras模型的输出层,并设置该神经元的初始权重和偏差.
Specifically I would like to append an output neuron to the output layer of the Keras model and set that neuron's initial weights and bias.
推荐答案
偶然发现了我自己的问题的答案.谢谢大家的回答/评论.
Stumbled upon the answer to my own question. Thanks everyone for the answers/comments.
https://keras.io/layers/about-keras-layers/
此源代码的前几行详细介绍了如何加载和设置权重.本质上,可以通过加载旧的输出层,附加新的权重并为新层设置权重来将输出神经元附加到Keras模型.代码在下面.
The first few lines of this source detail how to load and set weights.Essentially, appending an output neuron to a Keras model can be accomplished by loading the old output layer, appending the new weights, and setting weights for a new layer. Code is below.
# Load weights of previous output layer, set weights for new layer
old_layer_weights = model.layers.pop().get_weights()
new_neuron_weights = np.ndarray(shape=[1,bottleneck_size])
# Set new weights
# Append new weights, add new layer
new_layer = Dense(num_classes).set_weights(np.append(old_layer_weights,new_neuron_weights))
model.add(new_layer)
这篇关于向Keras模型层添加新单元并更改其权重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!