gpt4 book ai didi

python - 如何在基于 Keras 的 CNN 中包含自定义过滤器?

转载 作者:行者123 更新时间:2023-12-03 23:21:48 24 4
gpt4 key购买 nike

我正在研究用于 CNN 的模糊卷积滤波器。我已经准备好了函数 - 它接受 2D 输入矩阵和 2D 核/权重矩阵。该函数输出卷积特征或激活图。

现在,我想使用 Keras 构建 CNN 的其余部分,这些 CNN 也将具有标准的 2D 卷积滤波器。

有什么方法可以将我的自定义过滤器插入到 Keras 模型中,使内核矩阵由 Keras 后端的内置库更新?或者,是否有任何库可用于在每次迭代时更新内核?

最佳答案

假设我们要应用 3x3 自定义过滤器 6x6 图片 .

enter image description here

必要进口

import keras.backend as K
import numpy as np
from keras import Input, layers
from keras.models import Model

自定义过滤器的定义

enter image description here

# 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 channel 图像。所以维度将是 6x6x1 。这里,像素值是随机整数。通常像素值应该是 0 to 2550.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))

虚拟转换模型 我们将在哪里使用我们的自定义过滤器

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.]]]]

关于python - 如何在基于 Keras 的 CNN 中包含自定义过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51930312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com