在 Keras (Theano) 的卷积层中填充均匀的内核大小

Padding with even kernel size in a convolutional layer in Keras (Theano)

我现在需要了解如何使用以 Theano 作为后端的 Keras 在一维卷积层中填充数据。我使用 "same" 填充。

假设我们有 8 的 output_length 和 4 的 kernel_size。根据 the original Keras code 我们有 8//4 == 2 的 padding。但是,当在我的水平数据的左端和右端添加两个零时,我可以计算 9 个卷积而不是 8 个。

谁能解释一下数据是如何填充的?在何处添加零以及如何计算数据右侧和左侧的填充值数量?

如何测试keras填充序列的方式:

您可以做的一个非常简单的测试是创建一个具有单个卷积层的模型,将其权重强制为 1,将其偏差设置为 0,并为其提供一个输入以查看输出:

from keras.layers import *
from keras.models import Model
import numpy as np


#creating the model
inp = Input((8,1))
out = Conv1D(filters=1,kernel_size=4,padding='same')(inp)
model = Model(inp,out)


#adjusting the weights
ws = model.layers[1].get_weights()

ws[0] = np.ones(ws[0].shape) #weights
ws[1] = np.zeros(ws[1].shape) #biases

model.layers[1].set_weights(ws)

#predicting the result for a sequence with 8 elements
testData=np.ones((1,8,1))
print(model.predict(testData))

这段代码的输出是:

[[[ 2.] #a result 2 shows only 2 of the 4 kernel frames were activated
  [ 3.] #a result 3 shows only 3 of the 4 kernel frames were activated
  [ 4.] #a result 4 shows the full kernel was used   
  [ 4.]
  [ 4.]
  [ 4.]
  [ 4.]
  [ 3.]]]

所以我们可以得出结论:

  • Keras 在 执行卷积之前 添加填充,而不是之后。所以结果不是"zero"。
  • Keras平均分配padding,当有奇数时,它在前。

因此,它在应用卷积之前使输入数据看起来像这样

[0,0,1,1,1,1,1,1,1,1,0]