具有Keras张量流后端的复矩阵乘法

时间:2018-06-01 06:02:22

标签: tensorflow matrix keras matrix-multiplication

让矩阵F1的形状为(a * h * w * m),矩阵F2的形状为(a * h * w * n),矩阵G的形状为{{1} }}

我想实现以下公式,该公式使用Keras的张量流后端从(a * m * n)G的因子计算F1的每个因子。但是我对各种后端函数感到困惑,尤其是F2K.dot()

$$ G_ {k,i,j} = \ sum ^ h_ {s = 1} \ sum ^ w_ {t = 1} \ dfrac {F ^ 1_ {k,s,t,i} * F ^ 2_ {k,s,t,j}} {h * w} $$ ie:

enter image description here

(通过在$$中复制上述等式并将其粘贴到this site获得的图像)

有没有办法实现上述公式?提前谢谢。

1 个答案:

答案 0 :(得分:1)

使用Tensorflow tf.einsum()(您可以将其包裹在Keras的Lambda图层中):

import tensorflow as tf
import numpy as np

a, h, w, m, n = 1, 2, 3, 4, 5

F1 = tf.random_uniform(shape=(a, h, w, m))
F2 = tf.random_uniform(shape=(a, h, w, n))

G = tf.einsum('ahwm,ahwn->amn', F1, F2) / (h * w)

with tf.Session() as sess:
    f1, f2, g = sess.run([F1, F2, G])

    # Manually computing G to check our operation, reproducing naively your equation:
    g_check = np.zeros(shape=(a, m, n))
    for k in range(a):
        for i in range(m):
            for j in range(n):
                for s in range(h):
                    for t in range(w):
                        g_check[k, i, j] += f1[k,s,t,i] * f2[k,s,t,j] / (h * w)

    # Checking for equality:
    print(np.allclose(g, g_check))
    # > True
相关问题