我正在研究一种用于CNN的模糊卷积滤波器。我已经准备好了这个函数-它接受2D输入矩阵和2D内核/权重矩阵。该函数输出卷积特征或激活图。
现在,我想使用Keras来构建CNN的其余部分,它也将具有标准的2D卷积滤波器。
有没有什么方法可以将我的自定义过滤器插入到Keras模型中,这样内核矩阵就会由Keras后端的内置库更新?或者,有没有什么库可以用来在每次迭代中更新内核?
发布于 2019-08-27 17:12:07
假设我们想要将3x3
自定义过滤器应用于6x6
图像。
必要的导入
import keras.backend as K
import numpy as np
from keras import Input, layers
from keras.models import Model
自定义筛选器的定义
# custom filter
def my_filter(shape, dtype=None):
f = np.array([
[[[1]], [[0]], [[-1]]],
[[[1]], [[0]], [[-1]]],
[[[1]], [[0]], [[-1]]]
])
assert f.shape == shape
return K.variable(f, dtype='float32')
虚拟示例输入图像(它是1
通道图像。因此,维度将为6x6x1
。这里,像素值是随机整数。通常,像素值应为0 to 255
或0.0 to 1.0
。)
input_mat = np.array([
[ [4], [9], [2], [5], [8], [3] ],
[ [3], [6], [2], [4], [0], [3] ],
[ [2], [4], [5], [4], [5], [2] ],
[ [5], [6], [5], [4], [7], [8] ],
[ [5], [7], [7], [9], [2], [1] ],
[ [5], [8], [5], [3], [8], [4] ]
])
# we need to give the batch size.
# here we will just add a dimension at the beginning which makes batch size=1
input_mat = input_mat.reshape((1, 6, 6, 1))
虚拟conv模型,我们将在其中使用自定义过滤器
def build_model():
input_tensor = Input(shape=(6,6,1))
x = layers.Conv2D(filters=1,
kernel_size = 3,
kernel_initializer=my_filter,
strides=2,
padding='valid') (input_tensor)
model = Model(inputs=input_tensor, outputs=x)
return model
测试
model = build_model()
out = model.predict(input_mat)
print(out)
输出
[[[[ 0.]
[-4.]]
[[-5.]
[ 3.]]]]
https://stackoverflow.com/questions/51930312
复制相似问题