gpt4 book ai didi

python - 将多个张量成对相乘 keras

转载 作者:行者123 更新时间:2023-11-30 09:45:39 24 4
gpt4 key购买 nike

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

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

output=some_function()(lstm)

some_function() 应该做 h1*h2,h2*h3....hn-1*hn我发现How do I take the squared difference of two Keras tensors?没什么帮助,但因为我将有可训练的参数,所以我必须制作自己的图层。此外,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])

关于python - 将多个张量成对相乘 keras,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52941192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com