在尝试重新创建1D-CNN正在执行的操作时,我偶然发现了一些奇怪的内容。我使用了numpy函数np.convolve
来手动计算输入与过滤器的卷积。我意识到我的模型和numpy函数的各自输出差异很大。原则上的Conv1D
层不应该这样做吗?
这是一个最小的工作示例:
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras import backend as K
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D
# Build a model consisting only of 1 convolutional layer with only 1 filter of length 2 (no bias used)
cnn = Sequential()
cnn.add(Conv1D(filters=1, kernel_size=2, strides=1, padding="valid",use_bias=False, input_shape=(10, 1)))
cnn.summary()
# Get the weights of the layer
w = cnn.layers[0].get_weights()[0][:, :, :]
# Create a random input vector
my_input = np.random.random([1,10,1])
# Create a function to get the output of a layer
get_output = K.function([cnn.layers[0].input],[cnn.layers[0].output])
# Feed the input into the layer and obtain output (convolution of input and the only weight)
output_mod = np.reshape(np.transpose(get_output([my_input])[0])[0],-1,1)
print(output_mod)
# Manually recreate the scenario with the numpy function
output_man = np.convolve(my_input[0,:,0],w[:,0,0],'valid')
print(output_man)
# Plot both convolutions
plt.plot(output_man)
plt.plot(output_mod)
plt.show()