4D矩阵乘法

时间:2018-03-07 11:25:12

标签: python numpy matrix-multiplication

我一直未找到使用numpy编写以下for循环的好方法。它现在写的方式当然非常低效,对于我的真实数据(形状512 * 8 * 8 * 512)是不可行的,但我只是没有有效地使用内置的矩阵乘法函数。

import numpy as np
#Create pseudo weights, biases, input
weights = np.random.rand(10, 8, 8, 10)
biases = np.random.rand(10)
pseudo_input = np.random.rand(10, 8, 8)
output_loops = np.zeros((weights.shape[0],))

for n in range(10):
    output_loops[n] += biases[n]
    for x in range(8):
        for y in range(8):
            for f in range(10):
                output_loops[n] += weights[f, x, y, n] * pseudo_input[f,x,y]

2 个答案:

答案 0 :(得分:4)

只需将相关迭代器移植到np.einsum中的einsum字符串表示法 -

np.einsum('fxyn,fxy->n', weights, pseudo_input) + biases

我们也可以使用np.tensordot -

np.tensordot(weights, pseudo_input, axes=((0,1,2),(0,1,2))) + biases

使用可靠的np.dot进行一些额外的重塑,将形状变为2D1D -

pseudo_input.ravel().dot(weights.reshape(-1,weights.shape[-1])) + biases

答案 1 :(得分:0)

另一种可能较慢的解决方案:

output_loops = (weights * pseudo_input[...,np.newaxis]).sum(axis=(0, 1, 2))
相关问题