Daedalus Crowley
Daedalus Crowley

Reputation: 31

Modify layer weights in Keras

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.

Upvotes: 3

Views: 1827

Answers (1)

alexhg
alexhg

Reputation: 799

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().

Upvotes: 3

Related Questions