Tensorflow:: 如何获得具有可训练参数的层

时间:2021-05-26 22:37:00

标签: tensorflow neural-network tensorflow2.0

我使用的是来自 TensorFlow 的预训练 Xception 模型。

base_model = keras.applications.Xception(
    weights='imagenet',
    input_shape=(150,150,3),
    include_top=False
)

它显示为 132 层:

len(base_model.layers)

但其中只有一部分具有可训练的参数(这 132 个包括激活层、MaxPool 和其他例如串联)。所以我的问题是:有没有办法只访问那些具有可训练参数的层(应该是其中的 71 个)?

2 个答案:

答案 0 :(得分:0)

试试这个

for layer in base_model.layers:
    if layer.trainable:
        print (layer.name)

答案 1 :(得分:0)

我自己找到了答案。它并不完美,但最接近我想要的。

from tensorflow.python.keras.utils.layer_utils import count_params

for layer in base_model.layers:
  if layer.count_params() > 0:
    print(layer.name)

它显示了 80 个层,其中包括 batch_normalization - 不知道为什么,我认为它们没有可训练的参数。