我怎样才能有效地扩展numpy中的因式张量?

时间:2014-07-15 20:31:02

标签: python performance numpy linear-algebra matrix-multiplication

我将三维张量考虑为三个二维矩阵,如本文中的等式22所示:http://www.iro.umontreal.ca/~memisevr/pubs/pami_relational.pdf

我的问题是,如果我想明确地计算张量,那么在numpy中有比这更好的方法吗?

W = np.zeros((100,100,100))
for i in range(100):
    for j in range(100):
        for k in range(100):
            W[i,j,k] = np.sum([wxf[i,f]*wyf[j,f]*wzf[k,f] for f in range(100)]) 

2 个答案:

答案 0 :(得分:2)

我倾向于使用einsum来解决这个问题,因为它通常最容易编写:

def fast(wxf, wyf, wzf):
    return np.einsum('if,jf,kf->ijk', wxf, wyf, wzf)

def slow(wxf, wyf, wzf):
    N = len(wxf)
    W = np.zeros((N, N, N))
    for i in range(N):
        for j in range(N):
            for k in range(N):
                W[i,j,k] = np.sum([wxf[i,f]*wyf[j,f]*wzf[k,f] for f in range(N)]) 
    return W

def gen_ws(N):
    wxf = np.random.random((N,N))
    wyf = np.random.random((N,N))
    wzf = np.random.random((N,N))
    return wxf, wyf, wzf

给出

>>> ws = gen_ws(25)
>>> via_slow = slow(*ws)
>>> via_fast = fast(*ws)
>>> np.allclose(via_slow, via_fast)
True

>>> ws = gen_ws(100)
>>> %timeit fast(*ws)
10 loops, best of 3: 91.6 ms per loop

答案 1 :(得分:1)

您的示例使用np.einsum()

提出解决方案非常简单
W = np.einsum('ij,jf,kf->ijk', wxf, wyf, wzf)