我正在使用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)
使用:
model.add(CustomConnected(units,matrixA))
model.add(CustomConnected(hidden_dim2, matrixB,activation='tanh')) #can use all the other named parameters...
请注意,所有神经元/单元最后都添加了偏差。如果您不希望出现偏见,则参数
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
其中
K
来自import keras.backend as K
。如果要查看矩阵掩盖的权重,还可以进一步设置自定义的
get_weights()
方法。 (在上面的第一种方法中没有必要)关于tensorflow - 在NN中指定连接(在keras中),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50290769/