【问题标题】:Complex matrix multiplication with tensorflow-backend of Keras复矩阵乘法与 Keras 的 tensorflow-backend
【发布时间】:2018-06-01 06:02:22
【问题描述】:

令矩阵F1的形状为(a * h * w * m),矩阵F2的形状为(a * h * w * n),矩阵G的形状为(a * m * n)

我想使用 Keras 的 tensorflow 后端实现以下公式,该公式根据 F1F2 的因子计算 G 的每个因子。但是我对各种后端功能感到困惑,尤其是K.dot()K.batch_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} $$ 即:

(将上述方程复制到$$中并粘贴到this site得到的图像)

有没有办法实现上面的公式?提前谢谢你。

【问题讨论】:

    标签: tensorflow matrix keras matrix-multiplication


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

    【讨论】:

    • 太棒了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 2016-06-04
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多