python-3.x - 如何在 keras 模型中可视化学习到的训练权重?

标签 python-3.x tensorflow keras jupyter-notebook

我想查看我的 keras 模型的可训练权重值,目标是查看训练后是否存在大块 0 或 1。

我的 keras 使用的是 tensorflow 后端。这是在 docker 图像中运行,并从 jupyter notebook 运行。

这是我已经走了多远。

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 或无穷大?

最佳答案

最简单的方法是评估权重张量:

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 来挑出有问题的值。

干杯

关于python-3.x - 如何在 keras 模型中可视化学习到的训练权重?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56208810/

相关文章:

python - 在 Python 中动态更改导入的引用

无法 pip 安装tensorflow-data-validation

python - 类型错误 : Input 'b' of 'MatMul' Op has type float32 that does not match type int32 of argument 'a'

python - Tensorflow Eager 和 Tensorboard 图?

python - keras/tensorflow 层的 "shape"和权重何时何地确定并存储?

python-3.x - LU 分解速度与传统 Ax=b 的比较

python - 如何在 Python 中制作固定大小的字节变量

tensorflow - Keras, tensorflow : Initializer for variable. .. 来自控制流结构、循环或条件

deep-learning - 如何找到 keras 模型的参数数量?

python - 了解 python 字典的顺序