Rol*_*ugu 2 keras tensorflow keras-layer
我正在使用keras和tensorflow 1.4。
我想明确指定两层之间连接的神经元。因此,每当第一层中的神经元i与第二层中的神经元j连接且在其他位置为零时,我就有一个矩阵A。
我的第一个尝试是创建一个带有内核的自定义层,该内核的大小与A相同,其中包含不可训练的零,其中A包含零,可训练的权重,其中A包含一个零。这样,所需的输出将是一个简单的点积。不幸的是,我没有设法弄清楚如何实现部分可训练和部分不可训练的内核。
有什么建议么?
(用很多神经元通过手工连接建立功能模型可能是一种解决方法,但是某种程度上是“丑陋”的解决方案)
如果矩阵的形状正确,我想到的最简单的方法是派生Dense层,并简单地在代码中添加矩阵并乘以原始权重:
class CustomConnected(Dense):
def __init__(self,units,connections,**kwargs):
#this is matrix A
self.connections = connections
#initalize the original Dense with all the usual arguments
super(CustomConnected,self).__init__(units,**kwargs)
def call(self,inputs):
#change the kernel before calling the original call:
self.kernel = self.kernel * self.connections
#call the original calculations:
super(CustomConnected,self).call(inputs)
Run Code Online (Sandbox Code Playgroud)
使用方法:
model.add(CustomConnected(units,matrixA))
model.add(CustomConnected(hidden_dim2, matrixB,activation='tanh')) #can use all the other named parameters...
Run Code Online (Sandbox Code Playgroud)
请注意,所有神经元/单位最后都添加了偏差。use_bias=False如果您不希望有偏见,则该参数仍然有效。例如,您也可以使用向量B进行完全相同的操作,并使用self.biases = self.biases * vectorB
测试提示:使用不同的输入和输出尺寸,因此可以确保矩阵A的形状正确。
我刚刚意识到我的代码可能有问题,因为我正在更改原始Dense层使用的属性。如果出现怪异的行为或消息,则可以尝试其他调用方法:
def call(self, inputs):
output = K.dot(inputs, self.kernel * self.connections)
if self.use_bias:
output = K.bias_add(output, self.bias)
if self.activation is not None:
output = self.activation(output)
return output
Run Code Online (Sandbox Code Playgroud)
哪里K来的import keras.backend as K。
get_weights()如果要查看矩阵掩盖的权重,也可以进一步设置自定义方法。(在上面的第一种方法中没有必要)
| 归档时间: |
|
| 查看次数: |
1185 次 |
| 最近记录: |