2017-06-20 192 views
2

我想通过在Keras中没有定义的特定内核初始化卷积层。举例来说,如果我定义了如下函数来初始化内核:如何用Keras中的任意内核初始化卷积层?

def init_f(shape): 
     ker=np.zeros((shape,shape)) 
     ker[int(np.floor(shape/2)),int(np.floor(shape/2))]=1 
     return ker 

而且卷积层设计如下:

model.add(Conv2D(filters=32, kernel_size=(3,3), 
         kernel_initializer=init_f(3))) 

我得到的错误:“无法解释初始化标识符:” 。
我跟随在类似的问题: https://groups.google.com/forum/#!topic/keras-users/J46pplO64-8 但我无法使它适应我的代码。 你能帮我定义Keras中的任意内核吗?

预先感谢您。

回答

1

几个项目来解决。我们从内核初始化器开始。从the documentation

If passing a custom callable, then it must take the argument shape (shape of the variable to initialize) and dtype (dtype of generated values)

所以它的签名应该成为:

def init_f(shape, dtype=None) 

功能将不dtype工作,但它是很好的做法,以保持它在那里。这样,你可以指定dtype到你的函数调用里面,例如:

np.zeros(shape, dtype=dtype) 

这也解决了你的第二个问题:shape参数是一个元组,所以你只需要直接把它传递给np.zeros和不需要制作另一个元组。

我猜你想初始化在中间的1内核,所以你也可以概括你的函数用它接收任何形状的工作:

ker[tuple(map(lambda x: int(np.floor(x/2)), ker.shape))]=1 

全部放在一起:

def init_f(shape, dtype=None): 
    ker = np.zeros(shape, dtype=dtype) 
    ker[tuple(map(lambda x: int(np.floor(x/2)), ker.shape))]=1 
    return ker 

最后一个问题。您需要将功能到层,而不是调用的结果:

model.add(Conv2D(filters=32, kernel_size=(3,3), 
        kernel_initializer=init_f)) 

层功能将通过参数init_f