TensorFlow - 了解 CNN 文本分类的过滤器和步幅形状

TensorFlow - Understanding filter and stride shapes for CNN text classification

我正在使用 TensorFlow 中的 CNNs 审查 Denny Britz 的 tutorial 关于 text 的分类。过滤器和步幅形状在图像域中非常有意义。但是,当涉及到文本时,我对如何正确定义步幅和过滤器形状感到困惑。考虑 Denny 代码中的以下两层:

# Create a convolution + maxpool layer for each filter size
pooled_outputs = []
for i, filter_size in enumerate(filter_sizes):
    with tf.name_scope("conv-maxpool-%s" % filter_size):
        # Convolution Layer
        filter_shape = [filter_size, embedding_size, 1, num_filters]
        W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")
        b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")
        conv = tf.nn.conv2d(
            self.embedded_chars_expanded,
                W,
                strides=[1, 1, 1, 1],
                padding="VALID",
                name="conv")
        # Apply nonlinearity
        h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
        # Maxpooling over the outputs
        pooled = tf.nn.max_pool(
            h,
            ksize=[1, sequence_length - filter_size + 1, 1, 1],
            strides=[1, 1, 1, 1],
            padding='VALID',
            name="pool")
        pooled_outputs.append(pooled)

self.embedded_chars_expanded的shape是[batch_size, max_sentence_length, embedding_size, 1]表示每个batch member是max_sentence_length x embedding_size

的单通道矩阵

过滤器

假设我的 filter_shape 是 [3, 50, 1, 16]。我将其解释为过滤器将一次滑过 3 个具有维度 50 的词向量。这是文本,因此 1 对应于单个输入通道(与 3RGB 相对)。最后,16 意味着我将在 conv layer.

中有 16 个过滤器

我的解释正确吗?

步幅

类似地,conv 和 pooling 层中的步幅形状都定义为 [1, 1, 1, 1]

这个形状的尺寸是否对应 filter_shape 的尺寸?

如果是这样,这就是我困惑的原因。看起来词向量表示的性质意味着步幅长度应该是 [1, embedding_size, 1, 1] 这意味着我想在每个过滤器的一个通道上一次移动 window 一个完整的词。

Filters

Have I interpreted this correctly?

是的,完全正确。

Strides

Does this shape's dimensions correspond to the dimensions of the filter_shape?

是的,它对应于您在输入嵌入上卷积过滤器的步幅。

It would seem that the nature of word vector representations means that the stride length should be [1, embedding_size, 1, 1] meaning I want to move the window one full word at-a-time over one channel for each filter.

注意填充策略——conv2d中的填充设置为VALID。这意味着不会有填充。由于嵌入维度中的过滤器大小完全覆盖了输入,因此它只能适合一次而不考虑沿该维度的步幅。

换句话说 - 您可以独立于步幅沿着嵌入维度进行一次卷积。