You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中滚动线性回归的最快高效实现方案咨询

寻求更快的滚动线性回归实现方式

我需要实现一种极快且高效的滚动线性回归方法。我查阅了两篇关于滚动线性回归的Stack Overflow帖子,原本推测numpy在计算速度上是最快的,但以我有限的Python能力测试后发现,处理同一组滚动数据时,以下三种方法的耗时完全相同。请问是否存在比这三种方法更快的实现方式?

测试代码如下:

########## testing time for pd rolling vs numpy rolling

def fitcurve(x_pts):
    poly = np.polyfit(np.arange(len(x_pts)), x_pts, 1)
    return np.poly1d(poly)[1]


win_ = 30
# tmp_ = data_.Close
tmp_ = pd.Series(np.random.rand(10000))
s_time = time.time()
roll_pd = tmp_.rolling(win_).apply(lambda x: fitcurve(x)).to_numpy()
print('pandas rolling time is', time.time() - s_time)
plt.show()
pd.Series(roll_pd).plot()

########
s_time = time.time()
roll_np = np.empty(0)
for cnt_ in range(len(tmp_)-win_):
    tmp1_ = tmp_[cnt_:cnt_+ win_]
    grad_ = np.linalg.lstsq(np.vstack([np.arange(win_), np.ones(win_)]).T, tmp1_, rcond = None)[0][0]
    roll_np = np.append(roll_np, grad_)

print('numpy rolling time is', time.time() - s_time)
plt.show()
pd.Series(roll_np).plot()

#################
s_time = time.time()
roll_st = np.empty(0)
from scipy import stats
for cnt_ in range(len(tmp_)-win_):
    slope, intercept, r_value, p_value, std_err = stats.linregress(np.arange(win_), tmp_[cnt_:cnt_ + win_])
    roll_st = np.append(roll_st, slope)
print('stats rolling time is', time.time() - s_time)
plt.show()
pd.Series(roll_st).plot()

内容的提问来源于stack exchange,提问作者Kiann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 15:10:31