我需要使用两个矩阵进行加权平均

I need make a weighted average using two matrix

我不是程序员,我是生物学家,我需要用两个矩阵制作以下内容:

matrix_de_pesos= np.array([[0.1, 0.2, 0.3],[0.4, 0.5, 0.6],[0.7, 0.8, 0.9]])
matrix_de_embeddings= np.array([[1,2,3],[4,5,6],[7,8,9],[10,20,30]])

一个矩阵包含权重和另一个嵌入。我需要将权重矩阵的每一列的每个元素乘以矩阵嵌入的每一列。然后对向量求和并除以嵌入矩阵的列总数。

我是这样做的:

n=[]
for j in range(matrix_de_pesos.shape[1]):
    auxiliar = np.zeros((matrix_de_embeddings.shape[0], matrix_de_embeddings.shape[1]))
    for i in range(matrix_de_pesos.shape[0]):
        for x in range(matrix_de_embeddings.shape[0]):
            auxiliar[x][i] = matrix_de_pesos[i][j]*matrix_de_embeddings[x][i]
    resultado = np.sum(auxiliar,axis=1)/auxiliar.shape[1]
    n.append(resultado)
matrix_final = np.array(n)
matrix_final = matrix_final.T
print(matrix_final)

结果是:

[[ 1.   1.2  1.4]
 [ 2.2  2.7  3.2]
 [ 3.4  4.2  5. ]
 [10.  12.  14. ]]

我的代码适用于这个小矩阵,但是当我将它用于我应该做的矩阵时,(这种形状:权重(55097, 15677)、嵌入(300, 55132)),代码非常非常慢。 我尝试使用函数 np.average 执行此操作,但我不明白代码是否有效。 我需要任何解决方案。 非常感谢大家。

你可以使用矩阵乘法

import numpy as np
print(np.matmul(matrix_de_embeddings,matrix_de_pesos)/matrix_de_embeddings.shape[1])

Numpy Matrix Multiplication