简体   繁体   English

将多个张量成对的keras相乘

[英]Multiply multiple tensors pairwise keras

I want to ask if it is possible to multiply two tensors pairwise. 我想问问是否可以将两个张量成对相乘。 So for example, I have tensor output from LSTM layer, 例如,我有LSTM层的张量输出,

lstm=LSTM(128,return_sequences=True)(input)

output=some_function()(lstm)

some_function() should do h1*h2,h2*h3....hn-1*hn I found How do I take the squared difference of two Keras tensors? some_function()应该做h1*h2,h2*h3....hn-1*hn我发现如何取两个Keras张量的平方差? little helpful but since, I will have trainable paramter, I will have to make my own layer. 几乎没有什么帮助,但是由于我将拥有可训练的参数,因此我将必须自己制作图层。 Also, will some_function layer interpret input dimension automatically as it will be hn-1 另外, some_function层会自动解释输入尺寸,因为它会是hn-1

I am confused on how to deal with call() 我对如何处理call()感到困惑

One possibility is to do two crop operations and then a multiplication. 一种可能性是先进行两次修剪操作,然后再进行一次乘法。 This does the trick! 这可以解决问题!

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


batch_size   = 1
nb_timesteps = 4
nb_features  = 2
hidden_layer = 2

in1 = Input(shape=(nb_timesteps,nb_features))

lstm=LSTM(hidden_layer,return_sequences=True)(in1)

# Make two slices
factor1 = Lambda(lambda x: x[:, 0:nb_timesteps-1, :])(lstm)
factor2 = Lambda(lambda x: x[:, 1:nb_timesteps, :])(lstm)

# Multiply them
out = Multiply()([factor1,factor2])

# set the two outputs so we can see both results
model = Model(in1,[out,lstm])

a = np.arange(batch_size*nb_timesteps*nb_features).reshape([batch_size,nb_timesteps,nb_features])

prediction = model.predict(a)
out_, lstm_ = prediction[0], prediction[1]


for x in range(nb_timesteps-1):
    assert all( out_[0,x] == lstm_[0,x]*lstm_[0,x+1])

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

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