简体   繁体   English

在张量流中使用Conv1d时如何实现平均池化?

[英]How to implement average pooling in case of Conv1d in tensorflow?

I want to implement the average pooling in conv1d. 我想在conv1d中实现平均池化。 But tf.nn.avg_pool function can only be implemented on 4 dimensional tensor. 但是tf.nn.avg_pool函数只能在4维张量上实现。 So what should I do to overcome this problem? 那我该怎么做才能克服这个问题呢?

def avg_pool(conv_out):
    return tf.nn.avg_pool(conv_out,ksize=[1,1,2,1],strides=[1,1,2,1],padding='SAME')

i = tf.constant([1, 0, 2, 3, 0, 1], dtype=tf.float32)

data   = tf.reshape(i, [1, int(i.shape[0]), 1], name='data')

kernel = tf.Variable(tf.random_normal([2,1,1]))

conv_out = tf.nn.conv1d(data, kernel, 2, 'VALID')
pool_out = avg_pool(conv_out)

One option is to add an additional dimension to your data and then remove it: 一种选择是向数据添加其他维度,然后将其删除:

def avg_pool(conv_out):
    conv_out_2d = conv_out[:, tf.newaxis]
    pool_out_2d = tf.nn.avg_pool(conv_out_2d,
                                 ksize=[1, 1, 2, 1],
                                 strides=[1, 1, 2, 1],
                                 padding='SAME')
    pool_out = pool_out_2d[:, 0]
    return pool_out

Another possibility is to use the generic tf.nn.pool : 另一种可能性是使用通用的tf.nn.pool

def avg_pool(conv_out):
    return tf.nn.pool(conv_out, window_shape=[2], pooling_type='AVG', padding='SAME')

Note in this case I am not including the stride because the default value matches what you used for your example, but you can modify it too if you want. 请注意,在这种情况下,我不包括跨度,因为默认值与示例所用的相匹配,但是您也可以根据需要对其进行修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM