以前上课的时候老师讲过,现在写论文需要用, 为了预测下一时刻数据的数值
rm(list=ls())
filter.self <-function(x,p,q,iter.max=10){
n<-length(x); phi <- rep(1/p,p) ; # 权数初值
x.max <- sum(x[1:p]^2) # 计算学习常数
for(i in 2:(n-p+1)){
temp<- sum(x[i:(i+p-1)]^2)
if(x.max<temp) x.max <- temp
}
k<- 1/x.max; cat("\nLearning constant:",k,"\n")
x.hat <- e <- numeric(n); iter <- 0;cri <- 1; mse <- 0
while(cri>1e-4 &&iter<iter.max){
cat("\n-----------------",iter+1,"th","--------------------------\n")
for(t in p:(n-1)){
x.hat[t+1] <- sum(x[t:(t-p+1)]*phi) # 预测
e[t+1]<- x[t+1]-x.hat[t+1] # 误差
phi<- phi + 2*k*e[t+1]*x[t:(t-p+1)]; cat(“phi:”,phi,“\n”) #更新权数值
}
iter<- iter + 1
cri<- abs(mse - sum(e[-(1:p)]^2)/(n-p)) # 检验mse变化大小
mse<- sum(e[-(1:p)]^2)/(n-p); cat("MSE:",cri,"\n")
}
x<- c(x,rep(0,q))
for(t in n:(n+q-1)){
x[t+1] <- sum(x[t:(t-p+1)]*phi) #预测未来
}
return(x)
}