gpt4 book ai didi

performance - 在移动窗口中找到最佳线性拟合

转载 作者:行者123 更新时间:2023-12-04 20:46:26 27 4
gpt4 key购买 nike

任务:在移动窗口中找到最佳线性拟合的斜率(例如,最小化误差方差)。 x 值是等距的,例如随着时间的推移自动测量。
问题:性能是一个问题,因为它需要对许多数据集重复。
天真的实现:循环 y 值。

#some data
x <- 0:(8*60)
set.seed(42)
y <- -x^2*0.01+x*20+rnorm(8*60+1,mean=300,sd=50)

plot(y~x,pch=".")

optWinLinFit0 <- function(x,y,win_length) {
xfit <- x[seq_len(win_length)]
xfit <- xfit-min(xfit)
#regression on moving window
res <- lapply(seq_len(length(x)-win_length),function(i,x,y) {
y <- y[seq_len(win_length)+i-1]
list(y=y,fit = lm.fit(cbind(1,xfit),y))
},x=x, y=y)
#find fit with smallest sigma^2
winner <- which.min(sapply(res,function(x) 1/(win_length-2)*sum(x$fit$residuals^2)))

y <- res[[winner]]$y
#return fit summary and predicted values
list(n=winner,summary=summary(lm(y~xfit)),
dat=data.frame(x=x[-seq_len(winner-1)][seq_len(win_length)],
y=y,
ypred=res[[winner]]$fit$fitted.values))
}
res0 <- optWinLinFit0(x,y,180)


lines(ypred~x,data=res0$dat,col="red",lwd=2)
红线给出了移动窗口位置的拟合值,其中误差方差最小:
enter image description here
任何想法如何更快地做到这一点?

最佳答案

你基本上是在做 kernel regression .有很多为此设计的函数和包:KernSmooth , gamlocfit浮现在脑海中。在基数 R 中,还有 loess (和 lowess ,旧版本)。更广泛地说,包 mgcv做同样的事情,但使用不同的基于样条的方法。

对于你在做什么,我会使用 gam::gammgcv::gam并在网格上的预测上使用有限差分。只有前者基于实际的局部回归,但它们都回答了所提出的问题。

我认为没有必要重新发明轮子。更重要的是,使用现有包意味着您将考虑端点处和曲线转折点处的偏差(局部线性拟合将围绕局部最大值/最小值偏置)等问题;要使用的加权方案;等等。您还可以利用标准工具进行模型构建和检查,例如交叉验证等。

关于performance - 在移动窗口中找到最佳线性拟合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17302625/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com