Tensorflow中CNN采用padding='same'时补零位置、卷积核位置

版权声明:本文为博主原创文章,转载请说明出处。 https://blog.csdn.net/kane7csdn/article/details/84892262

首先关于padding='same'的理解请参考TensorFlow中CNN的两种padding方式“SAME”和“VALID”

那么问题是,在采用padding='same'补零时,补零位置怎样分配?卷积核kernel的位置又在哪呢(与数据点如何对应)?

太长不看传送门:结论

(tensorflow version1.11.0)


数据长度为4,卷积核长度为3,步长为1,采用padding='same'补零时:

第一种可能——在数据末尾(或前端)补零,卷积核首位对应数据点

第二种可能——在数据两端补零,卷积核中心点对应数据点

import tensorflow as tf

inputs = tf.constant([1, 2, 3, 4], tf.float32)
inputs = tf.reshape(inputs, [1, 4, 1])

cnn = tf.layers.conv1d(
    inputs=inputs,
    filters=1,
    kernel_size=3,
    strides=1,
    padding='same',
    kernel_initializer='ones'
)
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    output = sess.run(cnn)
    print(output.reshape(-1))

设计一个实验,数据为[1, 2, 3, 4], 指定卷积核为[1, 1, 1]

结果是:

3 = 1*0+1*1+1*2,6=1*1+1*2+1*3,9=1*2+1*3+1*4,7=1*3+1*4+1*0

说明是在数据两端补零,卷积核中心点对应数据点。


数据长度为4,卷积核长度为2,步长为1,采用padding='same'补零时:

第一种可能:在数据末尾补零,卷积核首位对应数据点

第二种可能:在数据前端补零,卷积核末位对应数据点

import tensorflow as tf

inputs = tf.constant([1, 2, 3, 4], tf.float32)
inputs = tf.reshape(inputs, [1, 4, 1])

cnn = tf.layers.conv1d(
    inputs=inputs,
    filters=1,
    kernel_size=2,
    strides=1,
    padding='same',
    kernel_initializer='ones'
)
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    output = sess.run(cnn)
    print(output.reshape(-1))

设计一个实验,数据为[1, 2, 3, 4], 指定卷积核为[1, 1]

结果是:

3=1*1+1*2,5=1*2+1*3,7=1*3+1*4,4=1*4+1*0

说明是在数据末尾补零,卷积核首位对应数据点。


!!!但是在实际中,情况更为复杂,请参考下面的结论:


结论

Tensorflow使用这种方式,可以最大程度地使卷积核中心点对应数据点。

猜你喜欢

转载自blog.csdn.net/kane7csdn/article/details/84892262