【问题标题】:Tensorflow maxpool with dynamic ksize具有动态 ksize 的 TensorFlow maxpool
【发布时间】:2017-09-20 07:23:15
【问题描述】:

我在 TensorFlow 上有以下卷积层代码。该层是更大计算图的一部分。

# Define the shape of the filter
filter_shape = [1,
                config.char_filter_size,
                config.dim_char,
                config.dim_char]

# Define the convolutional layer weights and biases
W_conv = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1),
                     name="W_conv")
b_conv = tf.Variable(tf.constant(0.1, shape=[config.dim_char]),
                     name="b_conv")
# Do 2d convolution
conv = tf.nn.conv2d(char_embeddings,
                    W_conv,
                    strides=[1, 1, 1, 1],
                    padding="VALID",
                    name="conv")
# Apply nonlinearity
# h_conv has the same shape as conv
h_conv = tf.nn.relu(tf.nn.bias_add(conv, b_conv),
                    name="conv_relu")
# Maxpooling h_conv over dim 2 (char dim)

# ERROR HERE
conv_pooled = tf.nn.max_pool(h_conv,
                             ksize=[1, 1, tf.shape(h_conv)[-2], 1],
                             strides=[1, 1, 1, 1],
                             padding='VALID',
                             name="conv_max_pool")

尝试运行时,出现错误:

TypeError:参数“ksize”的预期 int 不是 tf.Tensor shape=() dtype=int32。

tf.nn.max_pool 无法处理动态ksize

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    问题不在于“动态 ksize”。 tf.nn.max_pool 接受

    长度 >= 4 的整数列表

    你有一个列表,但第三个元素是 not an integer 而是一个

    tf.int32 类型的张量。

    所以你应该在 session 中评估这个值,从中提取 int,然后才能使用它。

    【讨论】:

      【解决方案2】:

      您似乎只是想在可能具有动态大小的维度之一上找到最大值。 如果是这种情况,您最好使用tf.reduce_max() 函数而不是tf.nn.max_pool()

      tf.reduce_max(
          h_conv,
          axis=2,
          keep_dims=True
      )
      

      我设置了keep_dims=True,因为它对应于如果最大池工作会得到的结果,但如果设置keep_dims=False,结果可能更容易处理。

      【讨论】:

        【解决方案3】:

        如前所述,k_size 需要一个整数列表而不是张量列表。但是,应用了修复程序。您可以使用:

        from tensorflow.python.ops import gen_nn_ops
        conv_pooled = gen_nn_ops.max_pool_v2(
        conv,
        ksize=[1,1, tf.shape(h_conv)[-2], 1],
        strides=[1, 1, 1, 1],
        padding='VALID',
        name="pool")
        

        【讨论】:

        猜你喜欢
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-12
        • 1970-01-01
        • 2019-09-06
        • 1970-01-01
        • 2018-08-05
        相关资源
        最近更新 更多