具有动态 ksize 的 Tensorflow maxpool [英] Tensorflow maxpool with dynamic ksize

查看:28
本文介绍了具有动态 ksize 的 Tensorflow maxpool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code for a convolutional layer on TensorFlow. This layer is part of a larger computational graph.

# 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")

尝试运行时,出现错误:

When trying to run, I get the error:

TypeError: 参数 'ksize' 应为 int,而不是 tf.Tensor shape=() dtype=int32.

TypeError: Expected int for argument 'ksize' not tf.Tensor shape=() dtype=int32.

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

is tf.nn.max_pool unable to handle dynamic ksize?

推荐答案

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

It seems like you simply want to find the largest value over one of the dimensions which may be of dynamic size. If that is the case, you are probably better off using the tf.reduce_max() function instead of tf.nn.max_pool().

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

我设置了 keep_dims=True 是因为它对应于最大池化工作时你会得到的结果,但如果你设置 keep_dims=False.

I set keep_dims=True because it corresponds to what you would get if max pooling worked, but it is probably easier to work with the result if you set keep_dims=False.

这篇关于具有动态 ksize 的 Tensorflow maxpool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆