Skip to main content
 首页 » 编程设计

python之将大型 numpy 数组与自身相乘时出现奇怪的结果

2025年05月04日1452php

我在计算大型 Numpy 数组时遇到了奇怪的结果。

A=np.matrix('1 2 3;3 4 7;8 9 6')  
A=([[1, 2, 3], 
    [3, 4, 7], 
    [8, 9, 6]]) 

A * A 按预期完成点积:

A*A=([[ 31,  37,  35], 
    [ 71,  85,  79], 
    [ 83, 106, 123]]) 

但是对于更大的矩阵 200X200,我得到不同的响应:

B=np.random.random_integers(0,10,(n,n)) 
B=array([[ 2,  0,  6, ...,  7,  3,  7], 
   [ 4,  9,  1, ...,  6,  7,  5], 
   [ 3,  1,  8, ...,  7,  3,  8], 
   ...,  
   [ 8,  4, 10, ...,  5,  4,  4], 
   [ 6,  6,  3, ...,  7,  2,  9], 
   [ 2, 10, 10, ...,  5,  7,  4]]) 

现在用 B 乘以 B

B*B 
array([[  4,   0,  36, ...,  49,   9,  49], 
   [ 16,  81,   1, ...,  36,  49,  25], 
   [  9,   1,  64, ...,  49,   9,  64], 
   ...,  
   [ 64,  16, 100, ...,  25,  16,  16], 
   [ 36,  36,   9, ...,  49,   4,  81], 
   [  4, 100, 100, ...,  25,  49,  16]]) 

我得到每个元素的平方并且不是矩阵 * 矩阵 我做了什么不同?

请您参考如下方法:

您似乎使用 matrix 类型创建了 A,而 B 是 ndarray 类型( np.random.random_integers 返回一个数组,而不是矩阵)。运算符 * 对前者执行矩阵乘法,对后者执行逐元素乘法。

来自documentation np.matrix 的:

A matrix is a specialized 2-D array that retains its 2-D nature through operations. It has certain special operators, such as * (matrix multiplication) and ** (matrix power).

顺便说一句,如果您在同一操作中使用两种不同的类型,NumPy 将使用属于具有最高优先级的元素的运算符:

>>> A = np.matrix('1 2 3;3 4 7;8 9 6')  
>>> B = np.array(A) # B is of array type, A is of matrix type 
>>> A * B 
matrix([[ 31,  37,  35], 
        [ 71,  85,  79], 
        [ 83, 106, 123]]) 
 
>>> B * A 
matrix([[ 31,  37,  35], 
        [ 71,  85,  79], 
        [ 83, 106, 123]]) 
 
>>> A.__array_priority__ 
10.0 
>>> B.__array_priority__ 
0.0