如何计算两个Keras张量的平方差? [英] How do I take the squared difference of two Keras tensors?

查看:965
本文介绍了如何计算两个Keras张量的平方差?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Keras Model,它可以计算两个具有相同形状的张量r1r2.我想让模型计算(r1 - r2)**2.

I have a Keras Model which calculates two tensors, r1 and r2 of the same shape. I would like to have the model calculate (r1 - r2)**2.

我可以用keras.layers.add(r1, r2)取这些张量的总和.我可以用keras.layers.multiply(r1, r2)产品.如果有subtract函数,我会写

I can take the sum of these tensors with keras.layers.add(r1, r2). I can take a product with keras.layers.multiply(r1, r2). If there was a subtract function, I'd write

r = keras.layers.subtract(r1, r2)
square_diff = keras.layers.multiply(r, r)

,但似乎没有keras.layers.subtract函数.

作为替代,我一直试图找出如何将一个输入与一个恒定的-1张量相乘然后相加,但是我无法弄清楚如何创建该-1张量.我已经尝试了多种变体

In lieu of that I've been trying to figure out how to multiply one of my inputs by a constant -1 tensor and then adding, but I can't figure out how to create that -1 tensor. I've tried a number of variants on

negative_one = keras.backend.constant(np.full(r1.get_shape()), -1)

没有一项工作.大概是因为r1的维数是(?, 128)(即第一维是批处理大小,第二维代表128个隐藏元素).

none of which work. Presumably because the dimensionality of r1 is (?, 128) (i.e. the first dimension is a batch size, and the second represents 128 hidden elements.)

在Keras中采用两个张量之差的正确方法是什么?

What is the correct way in Keras to take the difference of two tensors?

推荐答案

我没有资格说这是否正确,但是下面的代码将根据您的要求计算(r1 - r2)**2.这里的关键实现因素是使用Keras功能API和 Lambda 层来反转输入张量.

I'm not qualified to say whether or not this is the correct way, but the following code will calculate (r1 - r2)**2 as you request. The key enabler here is the use of the Keras functional API and Lambda layers to invert the sign of an input tensor.

import numpy as np
from keras.layers import Input, Lambda
from keras.models import Model
from keras.layers import add

r1 = Input(shape=(1,2,2))
r2 = Input(shape=(1,2,2))

# Lambda for subtracting two tensors
minus_r2 = Lambda(lambda x: -x)(r2)
subtracted = add([r1,minus_r2])
out= Lambda(lambda x: x**2)(subtracted)

model = Model([r1,r2],out)

a = np.arange(4).reshape([1,1,2,2])
b = np.ones(4).reshape([1,1,2,2])

print(model.predict([a,b]))
# [[[[ 1.  0.]
#    [ 1.  4.]]]]

print((a-b)**2)
# [[[[ 1.  0.]
#    [ 1.  4.]]]]

这篇关于如何计算两个Keras张量的平方差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆