Tensorflow 控制Keras层中的信息流和选通因子

Tensorflow 控制Keras层中的信息流和选通因子,tensorflow,keras,conv-neural-network,keras-layer,Tensorflow,Keras,Conv Neural Network,Keras Layer,给定一个CNN架构,其中从一层到另一层的信息流由选通因子控制。 部分信息“g”被发送到下一层,剩余的“1-g”被发送到前一层,就像跳过连接一样 如何在Keras中实现这样的体系结构? 提前感谢使用函数式API模型 对于闸门自动分数g: from keras.models import Model from keras.layers import * inputTensor = Input(someInputShape) #the actual value valueTensor = Crea

给定一个CNN架构,其中从一层到另一层的信息流由选通因子控制。 部分信息“g”被发送到下一层,剩余的“1-g”被发送到前一层,就像跳过连接一样

如何在Keras中实现这样的体系结构?
提前感谢

使用函数式API模型

对于闸门自动分数g:

from keras.models import Model
from keras.layers import *

inputTensor = Input(someInputShape)

#the actual value
valueTensor = CreateSomeLayer(parameters)(inputTensor)

#the gate - this is the value of 'g', from zero to 1
gateTensor = AnotherLayer(matchingParameters, activation='sigmoid')(inputTensor)

#value * gate = fraction g
fractionG = Lambda(lambda x: x[0]*x[1])([valueTensor,gateTensor])

#value - fraction = 1 - g
complement = Lambda(lambda x: x[0] - x[1])([valueTensor,fractionG])

#each tensor may go into individual layers and follow individual paths:
immediateNextOutput = ImmediateNextLayer(params)(fractionG)
oneOfTheForwardOutputs = OneOfTheForwardLayers(params)(complement)

#keep going, make one or more outputs, and create your model:
model = Model(inputs=inputTensor, outputs=outputTensorOrListOfOutputTensors)    
为了给同一层提供两个输入,可以连接、求和、乘法等,使它们成为一个输入

#concat
joinedTensor = Concatenate(axis=optionalAxis)([input1,input2])

#add
joinedTensor = Add()([input1,input2])

#etc.....

nextLayerOut = TheLayer(parameters)(joinedTensor)
如果要手动控制“g”: 在这种情况下,我们所要做的就是用用户定义的gateTensor替换gateTensor:

import keras.backend as K

gateTensor = Input(tensor=K.variable([g]))
创建模型时,将此张量作为输入传递。因为它是张量输入,所以不会改变使用拟合方法的方式

model = Model(inputs=[inputTensor,gateTensor], outputs=outputTensorOrListOfOutputTensors)    

啊。。。。我想你应该让模型自己决定分数……我将创建一个手动细分的版本。更新了我的答案。请参见末尾。RuntimeError:图形断开连接:无法获取层输入_11处的张量值。访问以下以前的层时没有问题:['input_10','conv2d_10']好的,因为gateTensor实际上是一个输入,它应该进入模型创建。请参阅更新的答案。这将删除错误。但现在输出形状已从无,64,64,64更改为1,64,64,64。输出形状的第一个元素应为“无”,以接受任意数量的图像。