【问题标题】:How do I get the weights of a layer in Keras?如何在 Keras 中获取图层的权重?
【发布时间】:2017-09-28 15:05:48
【问题描述】:

我使用的是 Windows 10、Python 3.5 和 tensorflow 1.1.0。我有以下脚本:

import tensorflow as tf
import tensorflow.contrib.keras.api.keras.backend as K
from tensorflow.contrib.keras.api.keras.layers import Dense

tf.reset_default_graph()
init = tf.global_variables_initializer()
sess =  tf.Session()
K.set_session(sess) # Keras will use this sesssion to initialize all variables

input_x = tf.placeholder(tf.float32, [None, 10], name='input_x')    
dense1 = Dense(10, activation='relu')(input_x)

sess.run(init)

dense1.get_weights()

我收到错误:AttributeError: 'Tensor' object has no attribute 'weights'

我做错了什么,如何获得dense1 的权重?我看过 thisthis SO 帖子,但我仍然无法让它工作。

【问题讨论】:

    标签: python tensorflow deep-learning keras keras-layer


    【解决方案1】:

    如果你想得到所有层的权重和偏差,你可以简单地使用:

    for layer in model.layers: print(layer.get_config(), layer.get_weights())
    

    这将打印所有相关信息。

    如果你希望权重直接返回为 numpy 数组,你可以使用:

    first_layer_weights = model.layers[0].get_weights()[0]
    first_layer_biases  = model.layers[0].get_weights()[1]
    second_layer_weights = model.layers[1].get_weights()[0]
    second_layer_biases  = model.layers[1].get_weights()[1]
    

    等等

    【讨论】:

      【解决方案2】:

      如果你写:

      dense1 = Dense(10, activation='relu')(input_x)

      那么dense1 不是层,是层的输出。图层为Dense(10, activation='relu')

      看来你的意思是:

      dense1 = Dense(10, activation='relu')
      y = dense1(input_x)
      

      这是一个完整的sn-p:

      import tensorflow as tf
      from tensorflow.contrib.keras import layers
      
      input_x = tf.placeholder(tf.float32, [None, 10], name='input_x')    
      dense1 = layers.Dense(10, activation='relu')
      y = dense1(input_x)
      
      weights = dense1.get_weights()
      

      【讨论】:

      • 如果我想要多层,这样做的适当方法是什么? IE。有没有比y=dense2(dense1(input_x))更好的方法
      • 感谢您的解释。提供清晰度。
      【解决方案3】:

      如果您想查看您的层的权重和偏差如何随时间变化,您可以添加一个回调来记录它们在每个训练时期的值。

      以这样的模型为例,

      import numpy as np
      model = Sequential([Dense(16, input_shape=(train_inp_s.shape[1:])), Dense(12), Dense(6), Dense(1)])
      

      在拟合期间添加回调 **kwarg:

      gw = GetWeights()
      model.fit(X, y, validation_split=0.15, epochs=10, batch_size=100, callbacks=[gw])
      

      回调定义的地方

      class GetWeights(Callback):
          # Keras callback which collects values of weights and biases at each epoch
          def __init__(self):
              super(GetWeights, self).__init__()
              self.weight_dict = {}
      
          def on_epoch_end(self, epoch, logs=None):
              # this function runs at the end of each epoch
      
              # loop over each layer and get weights and biases
              for layer_i in range(len(self.model.layers)):
                  w = self.model.layers[layer_i].get_weights()[0]
                  b = self.model.layers[layer_i].get_weights()[1]
                  print('Layer %s has weights of shape %s and biases of shape %s' %(
                      layer_i, np.shape(w), np.shape(b)))
      
                  # save all weights and biases inside a dictionary
                  if epoch == 0:
                      # create array to hold weights and biases
                      self.weight_dict['w_'+str(layer_i+1)] = w
                      self.weight_dict['b_'+str(layer_i+1)] = b
                  else:
                      # append new weights to previously-created weights array
                      self.weight_dict['w_'+str(layer_i+1)] = np.dstack(
                          (self.weight_dict['w_'+str(layer_i+1)], w))
                      # append new weights to previously-created weights array
                      self.weight_dict['b_'+str(layer_i+1)] = np.dstack(
                          (self.weight_dict['b_'+str(layer_i+1)], b))
      

      此回调将构建一个包含所有层权重和偏差的字典,并由层号标记,因此您可以在训练模型时看到它们如何随时间变化。您会注意到每个权重和偏差数组的形状取决于模型层的形状。为模型中的每一层保存一个权重数组和一个偏置数组。第三个轴(深度)显示了它们随时间的演变。

      这里我们使用了 10 个 epoch 和一个具有 16、12、6 和 1 个神经元层的模型:

      for key in gw.weight_dict:
          print(str(key) + ' shape: %s' %str(np.shape(gw.weight_dict[key])))
      
      w_1 shape: (5, 16, 10)
      b_1 shape: (1, 16, 10)
      w_2 shape: (16, 12, 10)
      b_2 shape: (1, 12, 10)
      w_3 shape: (12, 6, 10)
      b_3 shape: (1, 6, 10)
      w_4 shape: (6, 1, 10)
      b_4 shape: (1, 1, 10)
      

      【讨论】:

      • 批量得到的矩阵也可以保存吗?还是经过一定数量的批次?
      【解决方案4】:

      如果图层索引号令人困惑,您也可以使用图层名称

      权重

      model.get_layer(<<layer_name>>).get_weights()[0]
      

      偏见

      model.get_layer(<<layer_name>>).get_weights()[1]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-04
        • 1970-01-01
        • 2020-04-01
        • 2020-08-09
        • 2017-03-22
        • 2017-10-07
        • 2019-11-18
        • 1970-01-01
        相关资源
        最近更新 更多