我正在使用 Conv2D
Keras 2.0
的型号.但是,我无法完全理解该函数在数学上的作用。我尝试使用随机生成的数据和一个非常简单的网络来理解数学:
import numpy as np
import keras
from keras.layers import Input, Conv2D
from keras.models import Model
from keras import backend as K
# create the model
inputs = Input(shape=(10,10,1)) # 1 channel, 10x10 image
outputs = Conv2D(32, (3, 3), activation='relu', name='block1_conv1')(inputs)
model = Model(outputs=outputs, inputs=inputs)
# input
x = np.random.random(100).reshape((10,10))
# predicted output for x
y_pred = model.predict(x.reshape((1,10,10,1))) # y_pred.shape = (1,8,8,32)
例如,我尝试计算第一个特征图中第一行、第一列的值,遵循 here 中的演示。 .
w = model.layers[1].get_weights()[0] # w.shape = (3,3,1,32)
w0 = w[:,:,0,0]
b = model.layers[1].get_weights()[1] # b.shape = (32,)
b0 = b[0] # b0 = 0
y_pred_000 = np.sum(x[0:3,0:3] * w0) + b0
但是
relu(y_pred_000)
不等于 y_pred[0][0][0][0]
.谁能指出我的理解有什么问题?谢谢你。
最佳答案
这很简单,它来自 Theano
昏暗的订购。应用过滤器的结果存储在所谓的 channel
中尺寸。如果是 TensorFlow
这是最后一个维度,这就是结果良好的原因。如果是 Theano
它是第二维(卷积结果的形状为 (cases, channels, width, height)
,因此为了解决您的问题,您需要将预测线更改为:
y_pred = model.predict(x.reshape((1,1,10,10)))
此外,您还需要更改在
Theano
中将权重作为权重的方式。有形状(output_channels, input_channels, width, height)
您需要将重量 setter/getter 更改为:w = model.layers[1].get_weights()[0] # w.shape = (32,1,3,3)
w0 = w[0,0,:,:]
关于Keras 中的 Conv2D 函数背后的数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43975923/