【问题标题】:Expand matrix based on vector基于向量展开矩阵
【发布时间】:2022-12-03 01:02:40
【问题描述】:

我想将矩阵 A 转换为矩阵 B

NumPy 是否有比以下方法更好/更有效的方法?

import numpy as np

a = np.array([[0.02, 0.05, 0.05],
              [0.35, 0.10, 0.45],
              [0.08, 0.25, 0.15]])

w = np.array([0.75, 0.25])

B = np.insert(a, 9, a[2, :]).reshape(4, 3)
B = np.insert(B.T, 12, B[:, 2]).reshape(4, 4).T
B[2:4, :] = np.multiply(B[2:4, :].T, w).T

【问题讨论】:

    标签: numpy


    【解决方案1】:

    .insert 在这里不是一个好的选择,因为每次您这样做时,numpy 都需要分配内存来创建一个全新的数组。相反,只需预先分配所需的数组大小,然后分配到它的切片。

    a = np.array([[0.02, 0.05, 0.05],
                  [0.35, 0.10, 0.45],
                  [0.08, 0.25, 0.15]])
    
    w = np.array([0.75, 0.25])
    
    b_shape = tuple(s + 1 for s in a.shape) # We need one more row and column than a
    
    b = np.zeros(b_shape)    # Create zero array of required shape
    
    b[:a.shape[0], :a.shape[1]] = a   # Set a in the top left corner
    
    b[:, -1] = b[:, -2]         # Set last column from second-last column
    b[-1, :] = b[-2, :]         # Set last row from second-last row
    
    b[-w.shape[0]:, :] = b[-w.shape[0]:, :] * w[:, None]  # Multiply last two rows with `w`
    

    w[:, None] 使 w 成为列向量(2x1 矩阵),numpy 广播形状以进行正确的元素乘法。

    这给了我们所需的b

    array([[0.02  , 0.05  , 0.05  , 0.05  ],
           [0.35  , 0.1   , 0.45  , 0.45  ],
           [0.06  , 0.1875, 0.1125, 0.1125],
           [0.02  , 0.0625, 0.0375, 0.0375]])
    

    【讨论】:

      猜你喜欢
      • 2015-05-07
      • 1970-01-01
      • 2014-03-19
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      相关资源
      最近更新 更多