如何使用Tensorflow张量设置功能模型的Keras层的输入?
我有两个要使用的软件包,一个是用Keras1.2编写的,另一个是用tensorflow编写的.我想将在tensorflow中构建的架构的一部分用于Keras模型中.
I have two packages I'd like to use, one is written in Keras1.2, and the other one in tensorflow. I'd like to use a part of the architecture that is built in tensorflow into a Keras model.
A partial solution is suggested here, but it's for a sequential model. The suggestion regarding functional models - wrapping the pre-processing in a Lambda layer - didn't work.
以下代码有效:
inp = Input(shape=input_shape)
def ID(x):
return x
lam = Lambda(ID)
flatten = Flatten(name='flatten')
output = flatten(lam(inp))
Model(input=[inp], output=output)
但是,当用预处理的输出张量flatten(lam(TF_processed_layer))
替换flatten(lam(inp))
时,我得到:模型的输出张量必须是Keras张量.找到:Tensor("Reshape:0",shape =(?, ?),dtype = float32)"
But, when replacing flatten(lam(inp))
with a pre-processed output tensor flatten(lam(TF_processed_layer))
, I got: "Output tensors to a Model must be Keras tensors. Found: Tensor("Reshape:0", shape=(?, ?), dtype=float32)"
您没有为Keras正确定义您的lamba. 尝试这样的事情
You are not defining your lamba correctly for Keras. Try something like this
def your_lambda_layer(x):
x -= K.mean(x, axis=1, keepdims=True)
x = K.l2_normalize(x, axis=1)
return x
....
model.add(Lambda(your_lambda_layer))
看到您正在使用功能性API
of seeing you are using the Functional API like this
def your_lambda_layer(x):
x -= K.mean(x, axis=1, keepdims=True)
x = K.l2_normalize(x, axis=1)
return x
....
x = SomeLayerBeforeLambda(options...)(x)
x = (Lambda(your_lambda_layer))(x)
但是,即使这样,lambda层也可能无法变平,因此请打印出lambda的形状并对其进行观察,看看它是什么.
But even so, the lambda layer may not be able to be flattened so printout the shape of the lambda and take a look at it and see what it is.