将Keras卷积内核初始化为numpy数组

2024-04-20 09:16:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将具有四个通道的(5,5)卷积层的权重初始化为numpy数组。该层的输入为形状(128128,1)。我特别希望:

def custom_weights(shape, dtype=None):
    matrix = np.zeros((1,5,5,4))
    matrix[0,2,2,0,0] = 1
    matrix[0,2,1,0,0] = -1

    matrix[0,2,2,0,1] = 1
    matrix[0,3,2,0,1] = -1

    matrix[0,2,2,0,2] = 2
    matrix[0,2,1,0,2] = -1
    matrix[0,2,3,0,2] = -1

    matrix[0,2,2,0,3] = 2
    matrix[0,1,2,0,3] = -1
    matrix[0,3,2,0,3] = -1
    weights = K.variable(matrix)
    return weights

input_shape = (128, 128, 1)
images = Input(input_shape, name='phi_input')

conv1 = Conv2D(4,[5, 5], use_bias = False, kernel_initializer=custom_weights, padding='valid', name='Conv2D_1', strides=1)(images)

然而,当我尝试这样做时,我得到一个错误

Depth of input (1) is not a multiple of input depth of filter (5) for 'Conv2D_1_19/convolution' (op: 'Conv2D') with input shapes: [?,128,128,1], [1,5,5,4].

我的错误是在权重矩阵的形状上吗


Tags: ofnamenumpyinput错误custom数组卷积
1条回答
网友
1楼 · 发布于 2024-04-20 09:16:36

您的代码中存在许多不一致(这导致了错误),您得到的错误不是来自给定的代码,因为它甚至没有正确地索引矩阵

matrix = np.zeros((1,5,5,4))
matrix[0,2,2,0,0] = 1

您正在初始化具有4个维度的numpy数组,但使用5个索引来更改值

您的内核权重维度错误。这是固定密码

from tensorflow.keras.layers import *
from tensorflow.keras import backend as K
import numpy as np

def custom_weights(shape, dtype=None):
    kernel = np.zeros((5,5,1,4))
    # change value here
    kernel = K.variable(kernel)
    return kernel

input_shape = (128, 128, 1)
images = Input(input_shape, name='phi_input')

conv1 = Conv2D(4,[5, 5], use_bias = False, kernel_initializer=custom_weights, padding='valid', name='Conv2D_1', strides=1)(images)

相关问题 更多 >