当包装函数需要非浮点参数时,Keras Lambda层中发生错误

时间:2019-09-17 12:17:04

标签: tensorflow lambda keras layer

我想根据文档将张量流函数包装在Keras Lambda层中。但是,我的输入很复杂。这是我用来复制此行为的代码的更完整示例:

import numpy as np
from keras.models import Model
from keras.layers import Input, Lambda
import tensorflow as tf
np.set_printoptions(precision=3, threshold=3, edgeitems=3)


def layer0(inp):
    z = inp[0] + inp[1]
    num = tf.cast(tf.real(z), tf.complex64)
    return z/num


if __name__ == "__main__":

    shape = (1,10,5)
    z1 = Input(shape=shape[1:], dtype=np.complex64)
    z2 = Input(shape=shape[1:], dtype=np.complex64)

    #s = Lambda(layer0, output_shape=shape)([z1, z2])
    s = Lambda(layer0)([z1, z2])

    model = Model(inputs=[z1,z2], outputs=s)

    z1_in = np.asarray(np.random.normal(size=shape) + np.random.normal(size=shape)*1j, 'complex64')
    z2_in = np.asarray(np.random.normal(size=shape) + np.random.normal(size=shape)*1j, 'complex64')

    s_out = model.predict([z1_in, z2_in])
    print(s_out)

出现以下错误:

Traceback (most recent call last):
  File "complex_lambda.py", line 32, in <module>
    s = Lambda(layer0)([z1, z2])
  File "complex_lambda.py", line 18, in layer0
    return z/num
TypeError: x and y must have the same dtype, got tf.float32 != tf.complex64

但是,如果我改用注释行: s = Lambda(layer0, output_shape=shape)([z1, z2])

代码运行正常。似乎需要“ output_shape =(...)”以使lambda函数中的除法起作用。尽管此解决方案解决了单个输出变量的问题,但在具有多个输出时却不起作用。

1 个答案:

答案 0 :(得分:0)

我无法复制您的问题。您正在使用哪个版本的tensorflow?您使用的是keras软件包还是tensorflow.keras子模块?

无论如何,我认为您可以通过指定dtype层的Lambda来解决问题:s = Lambda(lambda x: tf.math.real(x[0] + x[1]), dtype='complex64')([z1, s2])