2017-05-01 48 views
0

考慮我的輸入數據input_a和input_b自定網點產品在Keras使用Lambda表達式

np.array([1,2,3,4,5,6,7,8,9,10,11,12]).reshape(2,3,2) 
array([[[ 1, 2], 
     [ 3, 4], 
     [ 5, 6]], 

     [[ 7, 8], 
     [ 9, 10], 
     [11, 12]]]) 

np.array([1,2,3,4,5,6,7,8,9,10,11,12]).reshape(2,3,2) 
array([[ 1, 1], 
     [-1, -1], 
     [ 1, -1]]) 

我想實現

np.einsum('kmn, mk -> mn', input_a, input_b) 
array([[ 15, 18], 
     [ 45, 52], 
     [ 91, 102]]) 

如何翻譯這拉姆達什麼keras中的圖層

什麼我已經試過到目前爲止

def tensor_product(x): 
    input_a = x[0] 
    input_b = x[1] 
    y = np.einsum('kmn, mk -> mn', input_a, input_b) 
    return y 

dim_a = Input(shape=(2,)) 
dim_b = Input(shape=(2,2,)) 
layer_3 = Lambda(tensor_product, output_shape=(2,))([dim_a, dim_b]) 
model = Model(inputs=[input_a, input_b], outputs=layer_3) 

謝謝

回答

1
from keras.layers import * 

def tensor_product(x): 
    a = x[0] 
    b = x[1] 
    b = K.permute_dimensions(b, (1, 0, 2)) 
    y = K.batch_dot(a, b, axes=1) 
    return y 

a = Input(shape=(2,)) 
b = Input(shape=(2,2,)) 
c = Lambda(tensor_product, output_shape=(2,))([a, b]) 
model = Model([a, b], c)