Skip to main content
 首页 » 编程设计

python之在不使用 np.tile() 或创建新向量的情况下将向量扩展 n 次以适应更大的矩阵

2025年02月15日6rubylouvre

我有矩阵 (shape=3,12)并想用向量进行列到列的乘法 kkk (len=6) .我可以通过制作 np.tile(kkk,2) 来做到这一点将其扩展为 12 元素向量。但我想知道有没有一种方法可以直接将它相乘而不使用 np.tile (或者我必须为乘法制作一个新向量的任何东西)?

>>> matrix=np.ones([3,12]) 
 
>>> kkk 
array([ 0.008,  0.595,  0.278,  0.103,  0.014,  0.002]) 
 
>>> matrix*np.tile(kkk,2) 
array([[ 0.008,  0.595,  0.278,  0.103,  0.014,  0.002,  0.008,  0.595, 0.278,  0.103,  0.014,  0.002], 
       [ 0.008,  0.595,  0.278,  0.103,  0.014,  0.002,  0.008,  0.595, 0.278,  0.103,  0.014,  0.002], 
       [ 0.008,  0.595,  0.278,  0.103,  0.014,  0.002,  0.008,  0.595, 0.278,  0.103,  0.014,  0.002]]) 

请您参考如下方法:

reshape 以将 matrix 的第二个轴分成两部分,最后一个轴的长度为 6,然后我们可以将其引入 kkk 的逐元素乘法 最后 reshape 回原来的形状 -

(matrix.reshape(3,2,6)*kkk).reshape(3,12) 

sample 运行-

In [47]: a = np.random.randint(0,9,(3,12)) 
 
In [48]: matrix = np.random.randint(0,9,(3,12)) 
 
In [49]: kkk = np.random.randint(0,9,(6)) 
 
# As proposed in this post 
In [50]: (matrix.reshape(3,2,6)*kkk).reshape(3,12) 
Out[50]:  
array([[21, 32,  1,  5,  8,  6, 12, 12,  2,  0, 16,  9], 
       [18, 12,  7,  8, 40, 24,  3, 12,  1,  2, 48, 15], 
       [15, 20,  1,  0, 16, 12,  3, 32,  7,  8, 48, 24]]) 
 
# As proposed in the question with tiling (for verification) 
In [52]: matrix*np.tile(kkk,2) 
Out[52]:  
array([[21, 32,  1,  5,  8,  6, 12, 12,  2,  0, 16,  9], 
       [18, 12,  7,  8, 40, 24,  3, 12,  1,  2, 48, 15], 
       [15, 20,  1,  0, 16, 12,  3, 32,  7,  8, 48, 24]])