如何在Keras模型中可视化已学习的训练权重?

3
我想查看我的Keras模型的可训练权重值,以确定是否存在大片的零或一。我的Keras使用tensorflow后端,在docker镜像中运行,并从jupyter笔记本中运行。以下是我所做的工作。print(model.summary())将产生所有可训练参数的列表。
_____________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 512, 512, 3)       0         
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 512, 512, 16)      448       
_________________________________________________________________
activation_1 (Activation)    (None, 512, 512, 16)      0         
_________________________________________________________________
batch_normalization_1 (Batch (None, 512, 512, 16)      64        
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 256, 256, 16)      0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 256, 256, 32)      4640  

model.trainable_weights让我可以查看底层的tensorflow变量。

[<tf.Variable 'conv2d_1/kernel:0' shape=(3, 3, 3, 16) dtype=float32_ref>,
 <tf.Variable 'conv2d_1/bias:0' shape=(16,) dtype=float32_ref>,
 <tf.Variable 'batch_normalization_1/gamma:0' shape=(16,) dtype=float32_ref>,
 <tf.Variable 'batch_normalization_1/beta:0' shape=(16,) dtype=float32_ref>,
 <tf.Variable 'conv2d_2/kernel:0' shape=(3, 3, 16, 32) dtype=float32_ref>,
 <tf.Variable 'conv2d_2/bias:0' shape=(32,) dtype=float32_ref>,

我该如何打印这些变量的值以查看有多少个出现了0、1或无穷大等异常值?
1个回答

4
最简单的方法是评估权重张量:
from keras import backend as K

for w in model.trainable_weights:
    print(K.eval(w))

K.eval(w)将返回一个numpy数组,因此您可以对其进行通常的检查,例如:

np.isnan(w)
np.isinf(w)
w == 0
w == 1

您可以使用np.anynp.argwhere来单独识别问题值。

干杯!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接