【问题标题】:Access filters within a convolutional layer - TensorFlow2访问卷积层中的过滤器 - TensorFlow2
【发布时间】:2021-09-11 18:25:39
【问题描述】:

我正在使用 TF2.5 和 Python3.8,其中 conv 层定义为:

Conv2D(
    filters = 64, kernel_size = (3, 3),
    activation='relu', kernel_initializer = tf.initializers.GlorotNormal(),
    strides = (1, 1), padding = 'same',
)

使用一批 60 个 CIFAR-10 数据集作为输入:

x.shape
# TensorShape([60, 32, 32, 3])

该层的输出体积保留了空间宽度和高度(32、32),并有 64 个过滤器/内核映射作为批处理应用于 60 个图像-

conv1(x).shape
# TensorShape([60, 32, 32, 64])

conv1.kernel.shape
# TensorShape([3, 3, 3, 64])

在这个输出中,第一个 (3, 3) 是在这个转换层中应用的过滤器/内核的空间宽度和高度。第三个 3 是指提供给该层的输入通道数,64 是指应用的过滤器数量。

如何访问此转换层中应用的 64 个过滤器?

目前我正在使用代码:

filters = conv1.kernel[:, :, 0, :]

filters.shape
# TensorShape([3, 3, 64])

这是正确的吗?另外,如何迭代这个 conv 层的 64 个不同的过滤器?

谢谢

【问题讨论】:

  • model.layers[3].get_weights()?
  • @NicolasGervais 这行不通。首先,model.layers[3].get_weights() 返回一个列表,其中第一个元素返回(例如)(3, 3, 64, 128),第二个元素返回 (128,)。所以这将是model.layers[3].get_weights()[0] 和model.layers[3].get_weights[1]。不,这不会返回我感兴趣的过滤器。

标签: python tensorflow keras conv-neural-network tensorflow2.0


【解决方案1】:

您可以将tf.split 与model.layers[...].get_weights() 一起使用

import tensorflow as tf

model = tf.keras.applications.MobileNetV2()

conv_layer = model.layers[1]

[weights] = conv_layer.get_weights()

list_of_filters = tf.split(weights, axis=-1, num_or_size_splits=weights.shape[-1])

这将返回一个包含 32 个过滤器的列表,形状为 TensorShape([3, 3, 3, 1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多