Python—Modify layer weights in Keras

Python—Modify layer weights in Keras … here is a solution to the problem.

Python—Modify layer weights in Keras

I’m trying to modify the output of a layer in Keras. I have an encoder that converts time series into latent space, and after that, for each compressed time series, 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)

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 when I can do this, because if I write a Lambda layer after ouput_d, I won’t have access to the weights.

Solution

I’ve found that the only way to do something like this is to implement the required functionality as a callback, where you can access the model, and thus via self.model.trainable_weights or self.model.get_weights().

Related Problems and Solutions