3

我需要提高算法的速度。该方法将两个矩阵作为参数并执行点乘。唯一的问题是元素必须在 GF(256) 中作为八位字节相乘,然后作为异或相加。由于我正在处理非常大的稀疏矩阵,因此性能很糟糕。

def matrix_oct_mult(U, V, OCT_EXP, OCT_LOG):
temp_sum = 0
if shape(U)[1] == None and shape(V)[1] == None:
    for i in range(len(U)):
        temp_sum = oct_sum(temp_sum, oct_mult(U[i], V[i], OCT_EXP, OCT_LOG))
    return temp_sum
assert shape(U)[1] == shape(V)[0], "Wrong size requirements for matrix dot multiplication"
temp_sum = 0
W = sp.lil_matrix((shape(U)[0], shape(V)[1]))
for i in range (shape(U)[0]):
    for z in range(shape(V)[1]):
        for j in range (shape(U)[1]):
             temp_sum = oct_sum(temp_sum, oct_mult(U[i, j], V[j, z], OCT_EXP, OCT_LOG))

        W[i, z] = temp_sum
        temp_sum = 0
return W

如您所见,我尝试使用 lil 类,但性能仍然很差。

有什么有效的解决方法吗?

4

1 回答 1

0

由于 Python 是解释型的,因此for众所周知,嵌套循环的性能很差。而 C 中的等效for循环会很快。所以最好的性能将来自编译的代码。

出于这个原因,我编写了一个名为galois的 Python 库,它扩展了 NumPy 数组以在 Galois 字段中进行操作。我用 Python 编写了代码,但 JIT 使用 Numba 对其进行了编译,因此 Galois 域算术与本机 NumPy 数组算术一样快或几乎一样快,请参阅此性能比较

+该库使用标准二元运算符( 、、@等)和正常的 NumPy 线性代数函数支持伽罗瓦域矩阵上的线性代数。大多数这些例程也是为提高速度而编译的 JIT。

我相信您正在尝试对两个矩阵 ( (M,N) x (N,K)) 进行矩阵乘法。这是一个在galois.

In [1]: import galois                                                                                                                                                                          

# Create the GF(2^8) field using AES's irreducible polynomial -- your's may be different
In [2]: GF = galois.GF(2**8, irreducible_poly=0x11b)                                                                                                                                           

In [3]: print(GF.properties)                                                                                                                                                                   
GF(2^8):
  characteristic: 2
  degree: 8
  order: 256
  irreducible_poly: x^8 + x^4 + x^3 + x + 1
  is_primitive_poly: False
  primitive_element: x + 1

In [4]: A = GF.Random((3,4)); A                                                                                                                                                                
Out[4]: 
GF([[ 35, 130, 167, 111],
    [ 58, 161, 194, 200],
    [244,  65, 160,   8]], order=2^8)

In [5]: B = GF.Random((4,5)); B                                                                                                                                                                
Out[5]: 
GF([[ 50,  59,  23,  34,  38],
    [ 16,  59, 162,  80, 250],
    [205, 145, 114,   9,  40],
    [212, 250, 162, 210,  72]], order=2^8)

In [6]: A @ B                                                                                                                                                                                  
Out[6]: 
GF([[144, 236, 142,  90,  89],
    [ 83, 171,  34,   2, 117],
    [192,   1,  20, 208, 127]], order=2^8)
于 2021-08-11T17:44:48.270 回答