タスク:移動ウィンドウで最適な線形近似 (誤差分散の最小化など) の勾配を見つけます。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)
赤い線は、誤差分散が最小である移動ウィンドウの位置での適合値を示します。
これをより速く行う方法はありますか?