【问题标题】:How to set the input of a Keras layer of a functional model, with a Tensorflow tensor?如何使用 Tensorflow 张量设置功能模型的 Keras 层的输入?
【发布时间】:2017-10-24 09:51:45
【问题描述】:

我有两个想要使用的包,一个是用 Keras1.2 编写的,另一个是用 tensorflow 编写的。我想使用在 tensorflow 中构建的架构的一部分到 Keras 模型中。

建议使用部分解决方案here,但它适用于顺序模型。关于功能模型的建议 - 将预处理包装在 Lambda 层中 - 不起作用。

以下代码有效:

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)"

【问题讨论】:

  • 你找到答案了吗?

标签: tensorflow keras keras-layer


【解决方案1】:

您可以尝试将输入张量包装到 Keras 输入层中,然后从那里继续构建您的模型。像这样:

inp = Input(tensor=tftensor,shape=input_shape)
def ID(x):
    return x
lam = Lambda(ID)  
flatten = Flatten(name='flatten')
output = flatten(lam(inp))
Model(input=inp, output=output)

【讨论】:

    【解决方案2】:

    您没有为 Keras 正确定义您的 Lamba。 试试这样的

    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

    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 的形状并查看它,看看它是什么。

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 2022-11-11
      • 2016-11-29
      • 1970-01-01
      • 2019-11-17
      • 2019-04-23
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多