【问题标题】:custom matrix multiplication with numpy使用 numpy 自定义矩阵乘法
【发布时间】:2019-09-22 22:48:18
【问题描述】:

我想要一个奇怪的点积,用于 numpy 中的矩阵乘法。 对于矩阵A 的一行[1,2,3] 和矩阵B 的一列[4,5,6],我希望使用“产品”min(1+4, 2+5, 3+6) 来获得矩阵产品AB

【问题讨论】:

  • 添加最小样本数据和预期输出?

标签: python numpy matrix-multiplication


【解决方案1】:
In [498]: A = np.arange(12).reshape(4,3)                                             
In [499]: B = np.arange(4,10).reshape(3,2)                                           
In [500]: A                                                                          
Out[500]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])
In [501]: B                                                                          
Out[501]: 
array([[4, 5],
       [6, 7],
       [8, 9]])

参考迭代解决方案:

In [504]: res = np.zeros((A.shape[0],B.shape[1]), A.dtype) 
     ...: for i,row in enumerate(A): 
     ...:     for j,col in enumerate(B.T): 
     ...:         res[i,j] = np.min(row+col) 
     ...:                                                                            
In [505]: res                                                                        
Out[505]: 
array([[ 4,  5],
       [ 7,  8],
       [10, 11],
       [13, 14]])

使用广播的更快版本:

In [506]: np.min(A[:,:,None]+B[None,:,:], axis=1)                                    
Out[506]: 
array([[ 4,  5],
       [ 7,  8],
       [10, 11],
       [13, 14]])

===

证明矩阵乘积的等价性:

In [507]: np.dot(A,B)                                                                
Out[507]: 
array([[ 22,  25],
       [ 76,  88],
       [130, 151],
       [184, 214]])
In [508]: np.sum(A[:,:,None]*B[None,:,:], axis=1)                                    
Out[508]: 
array([[ 22,  25],
       [ 76,  88],
       [130, 151],
       [184, 214]])

【讨论】:

    【解决方案2】:

    您可以使用循环和 numpy 构建自己的自定义乘法函数,如下所示:

    import numpy as np
    
    x = np.array([[1, 2, 3], 
                  [4 ,5, 6], 
                  [7 ,8, 9]])
    
    y = np.array([[4, 0, 6], 
                  [5, 7, 3], 
                  [6, 5, 9]])
    
    def custom_multiply(x, y):
        return np.array([min(row*column) for row in x for column in y.T]).reshape(x.shape[0], y.shape[1])
    
    print(custom_multiply(x, y))
    

    输出:

    [[ 4  0  6]
     [16  0 15]
     [28  0 24]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多