将多个张量成对的keras相乘

时间:2018-10-23 04:30:23

标签: python tensorflow machine-learning keras lstm

我想问问是否有可能将两个张量成对相乘。例如,我有LSTM层的张量输出,

CustomActionTableViewController

view应该做alpha 我发现How do I take the squared difference of two Keras tensors?几乎没有什么帮助,但是由于我将拥有可训练的参数,因此我将不得不制作自己的图层。另外,lstm=LSTM(128,return_sequences=True)(input) output=some_function()(lstm) 层会自动解释输入尺寸,就像它是some_function()

我对如何处理h1*h2,h2*h3....hn-1*hn

感到困惑

1 个答案:

答案 0 :(得分:1)

一种可能性是先进行两次修剪操作,然后再进行乘法。 这样就可以了!

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