【问题标题】:Multiply multiple tensors pairwise keras将多个张量成对相乘 keras
【发布时间】:2019-03-27 05:28:07
【问题描述】:

我想问两个张量是否可以成对相乘。例如,我有来自 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()感到困惑

【问题讨论】:

    标签: python tensorflow machine-learning keras lstm


    【解决方案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])
    

    【讨论】:

    • 我认为您的out 将包含隐藏输入之间的详尽乘法,而不是所需问题的答案。 out 的维度将以 ?,9,1 作为维度。
    猜你喜欢
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 2019-02-10
    • 2020-10-14
    • 1970-01-01
    • 2021-03-05
    • 2021-05-05
    • 2018-02-24
    相关资源
    最近更新 更多