了解卷积神经网络中的过滤器功能

数据挖掘 美国有线电视新闻网 卷积
2022-03-07 18:42:19

我正在尝试遵循可通过此链接访问的以下教程。

在第三个标题“3.​​ 可视化每个过滤器的激活图”下,我们可以看到以下功能:

def apply_filter(img, index, filter_list, ax):
    # set the weights of the filter in the convolutional layer to filter_list[i]
    model.layers[0].set_weights([np.reshape(filter_list[i], (4,4,1,1)), np.array([0])])
    # plot the corresponding activation map
    ax.imshow(np.squeeze(model.predict(np.reshape(img, (1, img.shape[0], img.shape[1], 1)))), cmap='gray')

我明白他们想要做什么。他们正在应用过滤器并尝试在此之后显示输出。但是,我不明白的是以下行:

model.layers[0].set_weights([np.reshape(filter_list[i], (4,4,1,1)), np.array([0])])

在这里分配权重是什么意思,为什么他们要重新塑造属于 to 的过滤4*44*4*1*1

2个回答

Keras 层上的函数set_weights需要输入的形状与您要替换的权重的形状相匹配。get_weights您可以通过调用您感兴趣的图层上的方法来找出这些维度。

在那个教程中,它看起来像下面这样。我们只需要 get_weights() 返回的第一个元素,因此[0]. 然后我们看到它的形状:

In [7]: model.layers[0].get_weights[0].shape
(4, 4, 1, 1)

因此,编写该教程的人需要匹配该形状,并且由于它只考虑定义模型的一层,因此可以在他们的示例中对其进行硬编码。


以下是我上面提到的两个主要函数的文档字符串:

设置权重()

In [8]: l1.set_weights?

Signature: l1.set_weights(weights)
Docstring:
Sets the weights of the layer, from Numpy arrays.

# Arguments
    weights: a list of Numpy arrays. The number
        of arrays and their shape must match
        number of the dimensions of the weights
        of the layer (i.e. it should match the
        output of `get_weights`).

# Raises
    ValueError: If the provided weights list does not match the
        layer's specifications.

get_weights()

In [9]: l1.get_weights?
Signature: l1.get_weights()
Docstring:
Returns the current weights of the layer.

# Returns
    Weights values as a list of numpy arrays

那行代码将filter_vals列表中的过滤器转换为与 2D 卷积层对应的权重,因此您可以看到将计算机视觉中的一些传统过滤器应用于图像的情况。您看到的输出是在通过该层的图像上应用显示的过滤器后该层将产生的输出。

重塑是必要的,因为 Keras 需要通道的维度(我们只有一个通道,因为它是灰度图像)和批处理,这就是代码添加这两个虚拟维度的原因。

该功能也有一个错误:

model.layers[0].set_weights([np.reshape(filter_list[i], (4,4,1,1)), np.array([0])])

应该

model.layers[0].set_weights([np.reshape(filter_list[index], (4,4,1,1)), np.array([0])])

希望有帮助!