Python 四维矩阵乘法

Python 四维矩阵乘法,python,numpy,matrix-multiplication,Python,Numpy,Matrix Multiplication,我一直没有找到一个好方法来使用numpy编写下面的循环。现在写它的方式当然是非常低效的,对于我的真实数据(形状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(1

我一直没有找到一个好方法来使用numpy编写下面的循环。现在写它的方式当然是非常低效的,对于我的真实数据(形状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]

只需将相关迭代器移植到-

我们也可以使用-

使用可靠的
np.dot
和一些额外的整形,使形状变成
2D
1D
-

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

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

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

这次你真的比我快了一秒钟。呸!多好的回答啊。
pseudo_input.ravel().dot(weights.reshape(-1,weights.shape[-1])) + biases
output_loops = (weights * pseudo_input[...,np.newaxis]).sum(axis=(0, 1, 2))