簡體   English   中英

將多個張量成對的keras相乘

[英]Multiply multiple tensors pairwise keras

我想問問是否可以將兩個張量成對相乘。 例如,我有LSTM層的張量輸出,

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

output=some_function()(lstm)

some_function()應該做h1*h2,h2*h3....hn-1*hn我發現如何取兩個Keras張量的平方差? 幾乎沒有什么幫助,但是由於我將擁有可訓練的參數,因此我將必須自己制作圖層。 另外, some_function層會自動解釋輸入尺寸,因為它會是hn-1

我對如何處理call()感到困惑

一種可能性是先進行兩次修剪操作,然后再進行一次乘法。 這可以解決問題!

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