重新实现矩阵乘法,可用来实现其他诡异的类似于矩阵乘法的操作

矩阵乘法\(C = AB\),其中
\(A\)\(m*n\)矩阵
\(B\)\(n*p\)矩阵

对于\(C_{ij}\)元素有 \(C_{i,j} = A_{i,*} · B_{*,j}\),其中 \(A_{i,*}\)代表\(A\)中第\(i\)行向量,\(B_{*,j}\)代表\(B\)中第\(j\)列向量
\(a = A_{i,*}\)\(b = B_{*,j}\),易知\(a\)\(b\)皆为\(n\)维向量,则
\(C_{i,j} = a · b = \sum_k^n{a_k * b_k}\)
-----上面都是矩阵乘法的废话(?
如何重新实现呢?答案是拓展维度,把\(A\)拓展成\(m*n*p\),把\(B\)拓展成\(m*n*p\)
那么此时原本\(A\)中的每一行都有和\(B\)中每一列的重叠,可以为所欲为了

具体实现:

import numpy as np

def matrix_mul(A, B):
    m, n = A.shape
    n, p = B.shape
    # 扩展A和B以匹配维度
    A_expanded = np.repeat(A[:, :, np.newaxis], p, axis=2)
    B_expanded = np.repeat(B[np.newaxis, :, :], m, axis=0)
    # 计算元素乘积
    mul = A_expanded * B_expanded
    # 计算和
    D = np.sum(mul, axis=1)
    return D

# 生成示例矩阵
A = np.random.randint(0, 5, (3, 4))
B = np.random.randint(0, 5, (4, 5))
# 运行运算
D = matrix_mul(A, B)
print(A)
print(B)
print(D)
E = np.matmul(A, B)
print(E)
# 输出0表示矩阵D和E完全相同
print(np.sum(D != E))

此时,如果我想实现一种类似于矩阵乘法的操作?使得\(D = A?B\),其中\(D_{i,j} = 1/n * \sum_k^n{Abs(a_k - b_k)}\),就很简单了
具体代码如下:

import numpy as np

def matrix_avg_diff(A, B):
    m, n = A.shape
    n, p = B.shape
    # 扩展A和B以匹配维度
    A_expanded = np.repeat(A[:, :, np.newaxis], p, axis=2)
    B_expanded = np.repeat(B[np.newaxis, :, :], m, axis=0)
    # 计算绝对差值
    diff = np.abs(A_expanded - B_expanded)
    # 计算平均值
    D = np.mean(diff, axis=1)
    return D

# 生成示例矩阵
A = np.random.randint(0, 5, (3, 4))
B = np.random.randint(0, 5, (4, 5))
# 运行运算
D = matrix_avg_diff(A, B)
print(A)
print(B)
print(D)
posted @ 2024-03-04 02:33  草帽过客  阅读(6)  评论(0编辑  收藏  举报