且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Keras中修改图层权重

更新时间:2023-12-01 21:36:34

我发现执行此操作的唯一方法是将所需功能实现为回调,您可以在其中进行访问通过 self.model.trainable_weights self.model.get_weights()来确定权重。 / p>

I'm trying to modify the output of a layer in Keras. I have an encoder which transforms a time series into latent space and after that, for each time series compressed I want to add some numbers to the time series.

For example I have:

input_d = Input((100,))
h1_d = Reshape((100, 1))(input_d)
h2_d = LSTM(150, return_sequences=True)(h1_d)
h3_d = TimeDistributed(Dense(64, activation='linear'))(h2_d)
h4_d = LSTM(150)(h3_d)
output_d = Dense(30, activation='linear')(h4_d)

And I want to do something like this:

new_weights = []
for i in outputs_d.weights:
    new_weights.append(np.vstack(([1,2,3], i)))

But the problem is that I don't know in which moment I can do this because if a write a Lambda layer after ouput_d I can't access the weights.

The only way I have found to do something like this is by implementing the desired functionality as a Callback, where you have access to the model and thus to the weights through self.model.trainable_weights or self.model.get_weights().