简体   繁体   English

Keras lambda层为l2范数

[英]Keras lambda layer for l2 norm

I just want to implement a custom layer for taking the l2 norm of two vectors (of matching dimensions of course) which were output by 2 different models in keras. 我只想实现一个自定义图层,用于获取两个矢量(当然是匹配尺寸)的l2范数,这两个矢量由keras中的2个不同模型输出。 I'm using the functional API method of writing keras functions, so I have stuff like: 我正在使用编写keras函数的函数API方法,所以我有类似的东西:

    inp1 = Input(someshape)
    X = Conv2D(someargs)(inp1)
    ...
    ...
    out1 = Dense(128)(X)

    inp2 = Input(someshape)
    Y = Conv2D(someargs)(inp2)
    ...
    ...
    out2 = Dense(128)(Y)

Then I want to take the l2 norm of the distance between out1 and out2 and feed it further into another network, so I have a lambda layer like: 然后我想取出out1和out2之间距离的l2范数并将其进一步输入另一个网络,所以我有一个lambda层,如:

    l2dist = keras.layers.Lambda(l2dist)(out1,out2)

Where l2dist is the function defined as: 其中l2dist是定义为的函数:

    def l2dist(x,y):
        return K.sqrt(K.sum((x-y)**2))

But I get an error for the l2dist =... line saying: 但我得到一个错误的l2dist = ...行说:

    TypeError: __call__() takes 2 positional arguments but 3 were given

I clearly only put 2 arguments, out1 and out2, why does python think I'm giving 3 arguments? 我显然只放了2个参数,out1和out2,为什么python认为我给出了3个参数?
I've tried this with a lambda function like: 我用lambda函数试过这个:

    l2dist = keras.layers.Lambda(lambda x,y: K.sqrt(K.sum((x-y)**2)))(out1,out2)

But I get the same error. 但我得到了同样的错误。

I discovered that the Lambda layer in keras can only accept one argument as input, so I have to input the lambda function as a function on a list and pass the two tensors in as a list. 我发现keras中的Lambda层只能接受一个参数作为输入,所以我必须将lambda函数作为函数输入到列表中,并将两个张量作为列表传递。 I also realized that I can't use the l2 norm since that only gives me 1 number to run the final layers on, I have to use a different distance function that can give an element wise distance rather than a Euclidean distance between two vectors. 我也意识到我不能使用l2范数,因为它只给我一个数字来运行最后一层,我必须使用一个不同的距离函数,它可以给出一个元素明智的距离而不是两个向量之间的欧几里德距离。 I'm now using the chi-squared distance, so my code looks like this and it runs (but it's giving me nan as a loss, but that's a different issue I guess. At least it runs): 我现在正在使用卡方距离,所以我的代码看起来像这样并且它运行(但是它给了我一个损失,但这是一个不同的问题我猜。至少它运行):

    chisqdist = keras.layers.Lambda(lambda x: (x[0]-x[1])**2/(x[0]+x[1]))([out1,out2])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM