【问题标题】:Avoiding for loop to run linear regression on 3d Array避免 for 循环在 3d 数组上运行线性回归
【发布时间】:2019-12-11 09:41:40
【问题描述】:

我需要在 3d-Array 中运行线性回归,例如:-

数组 = np.arange(3*4*5).reshape(3,4,5)

array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]],

       [[20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34],
       [35, 36, 37, 38, 39]],

      [[40, 41, 42, 43, 44],
       [45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54],
       [55, 56, 57, 58, 59]]])

我需要在 [0,20,40], [1,21,41] ....[5,25,45]....[19,39, 59] 上运行 LR 我正在使用以下代码:-

LrCalcRate = np.array([])
col_nums = 3
for j in range(Array.shape[1]):
    for i in range(Array.shape[2]):
        y = Array[:, j, i].T
        x = np.arange(col_nums)
        A = np.vstack([x, np.ones(len(x))]).T
        m, c = np.linalg.lstsq(A, y)[0]
        LrCalcRate = np.append(LrCalcRate, -m)

两个for循环很费时间,不使用for循环可以优化吗?

【问题讨论】:

  • 此示例不可重现。请定义col_numsnoisyMeasurementsnp
  • 这看起来你需要使用swapaxes 并从那里开始线性回归。但是例子太杂乱了,为什么不能适当地重塑?
  • 嗨@yatu,我已经更正了代码

标签: python arrays numpy linear-regression least-squares


【解决方案1】:

你写的等价于

x = np.arange(col_nums)
A = np.vstack([x, np.ones(len(x))]).T
-np.linalg.lstsq(A, a.reshape(a.shape[0], -1))[0][0]

例如,使用为每个目标生成不同斜率的数据:

In [9]: a = (np.linspace(0, 2, num=3*4*5)**2).reshape(3,4,5)                                

In [11]: lr_calc_rate = np.array([]) 
    ...: col_nums = 3 
    ...: for j in range(a.shape[1]): 
    ...:     for i in range(a.shape[2]): 
    ...:         y = a[:, j, i].T 
    ...:         x = np.arange(col_nums) 
    ...:         A = np.vstack([x, np.ones(len(x))]).T 
    ...:         m, c = np.linalg.lstsq(A, y)[0] 
    ...:         lr_calc_rate = np.append(lr_calc_rate, -m) 
    ...: lr_calc_rate

Out[11]: 
array([-0.91927607, -0.96523987, -1.01120368, -1.05716748, -1.10313128,
       -1.14909509, -1.19505889, -1.24102269, -1.2869865 , -1.3329503 ,
       -1.37891411, -1.42487791, -1.47084171, -1.51680552, -1.56276932,
       -1.60873312, -1.65469693, -1.70066073, -1.74662453, -1.79258834])

In [12]: x = np.arange(col_nums)
    ...: A = np.vstack([x, np.ones(len(x))]).T
    ...: -np.linalg.lstsq(A, a.reshape(3, -1))[0][0]

Out[12]: 
array([-0.91927607, -0.96523987, -1.01120368, -1.05716748, -1.10313128,
       -1.14909509, -1.19505889, -1.24102269, -1.2869865 , -1.3329503 ,
       -1.37891411, -1.42487791, -1.47084171, -1.51680552, -1.56276932,
       -1.60873312, -1.65469693, -1.70066073, -1.74662453, -1.79258834])

【讨论】:

  • 谢谢 fuglede,你能解释一下这是如何工作的吗?或者你能指导我吗
  • 嗯,它只是做你手工做的事情。来自the documentation:“如果 b 是二维的,则为 b 的每个 K 列计算最小二乘解” .
猜你喜欢
  • 2014-02-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-12
  • 1970-01-01
  • 2018-08-02
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多