簡體   English   中英

如何為每個輸入獲取 keras model 中層的權重

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

我知道您可以通過 Model.layer[layer_number].getWeights() 在某個點從 keras model 獲取層的權重。 我只是在訓練期間使用回調來獲得一個時期或一批的權重。

但我想獲得訓練部分中每個輸入的層權重。 或者如果可能的話,為每個輸入激活一個層而不是一個紀元。

有沒有辦法做到這一點?

這是一個小例子。 您可以使用custom callbacks ,您可以在其中按層訪問模型的權重(包括激活( layers.Activation ))。 只需根據您的需要進行更改。

這將在每個 epoch 后打印權重,您可以 plot 它們/也保存它們或根據需要對它們運行任何操作。

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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM