关于python:如何获取每个输入的keras模型中的图层权重

How to get the weights of layer in a keras model for each input

我知道您可以通过Model.layer [layer_number] .getWeights()在某个点上从keras模型中获取图层的权重。我只是在训练过程中使用回调获取某个时期或一批的权重。

但是我想获得训练部分中每个输入的图层权重。或者,如果可能的话,为每个输入激活一个层,而不是一个时期。

有没有办法实现这一目标?


这是一个小例子。您可以使用custom callbacks,在其中可以按层访问模型的权重(包括激活(layers.Activation))。只需根据您的需求进行更改。

这将在每个时期之后打印权重,如果需要,您可以绘制权重/也可以保存权重或对其进行任何操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.optimizers import Adam
import tensorflow as tf
import numpy as np
from keras.callbacks import LambdaCallback

model=Sequential()
model.add(Dense(32,activation='linear',input_shape=(37,10)))
model.add(Dense(32,activation='linear'))
model.add(Dense(10,activation='linear'))
model.compile(loss='mse',optimizer=Adam(lr=.001),metrics=['accuracy'])
model.summary()

class MyCustomCallback(tf.keras.callbacks.Callback):

  def on_train_batch_begin(self, batch, logs=None):
    print(model.layers[0].get_weights())

  def on_train_batch_end(self, batch, logs=None):
    print(model.layers[0].get_weights())

  def on_test_batch_begin(self, batch, logs=None):
    pass

  def on_test_batch_end(self, batch, logs=None):
    pass


X_train = np.zeros((10,37,10))
y_train = np.zeros((10,37,10))

weight_print = MyCustomCallback()
model.fit(X_train,
          y_train,
          batch_size=32,
          epochs=5,
          callbacks = [weight_print])