【问题标题】:Efficient way to do a large number of regressions using numpy?使用 numpy 进行大量回归的有效方法?
【发布时间】:2020-09-09 22:22:06
【问题描述】:

我有大量数据集(确切地说是 26,214,400 个)我想对其执行线性回归,即 26,214,400 个数据集中的每一个都由 n x 值和 n y 值组成,我想要找到y = m * x + b。对于任何一组点,我都可以使用sklearnnumpy.linalg.lstsq,例如:

A = np.vstack([x, np.ones(len(x))]).T
m, b = np.linalg.lstsq(A, y, rcond=None)[0]

有没有办法设置矩阵,这样我就可以避免 python 循环遍历 26,214,400 个项目?还是我必须使用循环并且使用 Numba 之类的东西会更好?

【问题讨论】:

  • 26,214,400个集合中的所有x值都一样吗?
  • @amazon-ex,不,很遗憾没有
  • 如果内存限制不是问题,我想您可以将由 x 数据和 1 组成的矩阵堆叠成一个(巨大的)块对角矩阵,并将您的 y 数据堆叠成一个向量,然后求解得到的线性方程。现在用一些虚拟数据测试它,如果它有效,我会回来:)

标签: python numpy regression


【解决方案1】:

我最终选择了numba 路线,该路线在我的笔记本电脑上产生了约 20 倍的速度,它使用了我所有的内核,所以我认为 CPU 越多越好。答案看起来像

import numpy as np
from numpy.linalg import lstsq
import numba

@numba.jit(nogil=True, parallel=True)
def fit(XX, yy):
    """"Fit a large set of points to a regression"""
    assert XX.shape == yy.shape, "Inputs mismatched"
    n_pnts, n_samples = XX.shape

    scale = np.empty(n_pnts)
    offset = np.empty(n_pnts)

    for i in numba.prange(n_pnts):
        X, y = XX[i], yy[i]
        A = np.vstack((np.ones_like(X), X)).T
        offset[i], scale[i] = lstsq(A, y)[0]

    return offset, scale

运行它:

XX, yy = np.random.randn(2, 1000, 10)                                   

offset, scale = fit(XX, yy)                                             

%timeit offset, scale = fit(XX, yy)                                     
1.87 ms ± 37.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

非jitted版本有这个时间:

41.7 ms ± 620 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

【讨论】:

  • 现在有点晚了,但结帐fastats,他们有一个OLS 实现,例如from fastats.linear_algebra import ols
猜你喜欢
  • 2018-08-09
  • 2011-02-17
  • 2018-02-03
  • 2017-02-06
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
  • 2019-12-01
相关资源
最近更新 更多