Tensorflow动态ksize的maxpool

6

我在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' 为整数类型,但传入的是形状为()、数据类型为int32的tf.Tensor。

tf.nn.max_pool 是否无法处理动态的 ksize
3个回答

6

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

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

我将keep_dims=True设置为了对应于最大池化的结果,但如果你将其设置为keep_dims=False,那么处理结果可能会更加容易。


3
问题不在于“动态ksize”。tf.nn.max_pool需要一个长度>=4的整数列表。您有一个列表,但第三个元素是Tensor类型的tf.int32,而不是整数。因此,您应该在会话中评估此值,从中提取int,然后才能使用它。

1
如先前所述,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")

这里有更多详细信息:https://github.com/tensorflow/tensorflow/pull/11875 - user3606057

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接