1 #' @include Forecaster.R
3 #' Neighbors2 Forecaster
5 #' Predict tomorrow as a weighted combination of "futures of the past" days.
6 #' Inherits \code{\link{Forecaster}}
8 Neighbors2Forecaster = R6::R6Class("Neighbors2Forecaster",
12 predictShape = function(data, today, memory, horizon, ...)
14 # (re)initialize computed parameters
15 private$.params <- list("weights"=NA, "indices"=NA, "window"=NA)
17 # Do not forecast on days with NAs (TODO: softer condition...)
18 if (any(is.na(data$getCenteredSerie(today))))
21 # Determine indices of no-NAs days followed by no-NAs tomorrows
22 fdays = getNoNA2(data, max(today-memory,1), today-1)
25 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "mix") #or "endo", or "exo"
26 kernel = ifelse(hasArg("kernel"), list(...)$kernel, "Gauss") #or "Epan"
29 return ( private$.predictShapeAux(data,
30 fdays, today, horizon, list(...)$h_window, kernel, simtype, TRUE) )
33 # Indices of similar days for cross-validation; TODO: 20 = magic number
34 cv_days = getSimilarDaysIndices(today, data, limit=20, same_season=FALSE, days_in=fdays)
36 # Function to optimize h : h |--> sum of prediction errors on last 45 "similar" days
37 errorOnLastNdays = function(h, kernel, simtype)
41 for (i in seq_along(cv_days))
43 # mix_strategy is never used here (simtype != "mix"), therefore left blank
44 prediction = private$.predictShapeAux(data,
45 fdays, cv_days[i], horizon, h, kernel, simtype, FALSE)
46 if (!is.na(prediction[1]))
48 nb_jours = nb_jours + 1
49 error = error + mean((data$getSerie(cv_days[i]+1)[1:horizon] - prediction)^2)
52 return (error / nb_jours)
55 if (simtype != "endo")
57 h_best_exo = optimize(
58 errorOnLastNdays, c(0,7), kernel=kernel, simtype="exo")$minimum
62 h_best_endo = optimize(
63 errorOnLastNdays, c(0,7), kernel=kernel, simtype="endo")$minimum
66 if (simtype == "endo")
68 return (private$.predictShapeAux(data,
69 fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
73 return (private$.predictShapeAux(data,
74 fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
78 h_best_mix = c(h_best_endo,h_best_exo)
79 return(private$.predictShapeAux(data,
80 fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
85 # Precondition: "today" is full (no NAs)
86 .predictShapeAux = function(data, fdays, today, horizon, h, kernel, simtype, final_call)
88 fdays_cut = fdays[ fdays < today ]
89 # TODO: 3 = magic number
90 if (length(fdays_cut) < 3)
93 # Neighbors: days in "same season"; TODO: 60 == magic number...
94 fdays = getSimilarDaysIndices(today, data, limit=60, same_season=TRUE, days_in=fdays_cut)
95 if (length(fdays) <= 1)
97 levelToday = data$getLevel(today)
98 distances = sapply(fdays, function(i) abs(data$getLevel(i)-levelToday))
99 #TODO: 2, 3, 5, 10 magic numbers here...
101 min_neighbs = min(3,length(fdays))
104 same_pollution = (distances <= dist_thresh)
105 nb_neighbs = sum(same_pollution)
106 if (nb_neighbs >= min_neighbs) #will eventually happen
108 dist_thresh = dist_thresh + 3
110 fdays = fdays[same_pollution]
112 if (nb_neighbs > max_neighbs)
114 # Keep only max_neighbs closest neighbors
115 fdays = fdays[ sort(distances[same_pollution],index.return=TRUE)$ix[1:max_neighbs] ]
117 if (length(fdays) == 1) #the other extreme...
121 private$.params$weights <- 1
122 private$.params$indices <- fdays
123 private$.params$window <- 1
125 return ( data$getSerie(fdays[1])[1:horizon] ) #what else?!
128 if (simtype != "exo")
130 h_endo = ifelse(simtype=="mix", h[1], h)
132 # Distances from last observed day to days in the past
133 serieToday = data$getSerie(today)
134 distances2 = sapply(fdays, function(i) {
135 delta = serieToday - data$getSerie(i)
139 sd_dist = sd(distances2)
140 if (sd_dist < .Machine$double.eps)
142 # warning("All computed distances are very close: stdev too small")
143 sd_dist = 1 #mostly for tests... FIXME:
147 exp(-distances2/(sd_dist*h_endo^2))
151 u = 1 - distances2/(sd_dist*h_endo^2)
157 if (simtype != "endo")
159 h_exo = ifelse(simtype=="mix", h[2], h)
161 M = matrix( nrow=1+length(fdays), ncol=1+length(data$getExo(today)) )
162 M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
163 for (i in seq_along(fdays))
164 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
166 sigma = cov(M) #NOTE: robust covariance is way too slow
167 # TODO: 10 == magic number; more robust way == det, or always ginv()
169 if (length(fdays) > 10)
174 # Distances from last observed day to days in the past
175 distances2 = sapply(seq_along(fdays), function(i) {
176 delta = M[1,] - M[i+1,]
177 delta %*% sigma_inv %*% delta
180 sd_dist = sd(distances2)
181 if (sd_dist < .25 * sqrt(.Machine$double.eps))
183 # warning("All computed distances are very close: stdev too small")
184 sd_dist = 1 #mostly for tests... FIXME:
188 exp(-distances2/(sd_dist*h_exo^2))
192 u = 1 - distances2/(sd_dist*h_exo^2)
199 if (simtype == "exo")
201 else if (simtype == "endo")
204 simils_endo * simils_exo
205 similarities = similarities / sum(similarities)
207 prediction = rep(0, horizon)
208 for (i in seq_along(fdays))
209 prediction = prediction + similarities[i] * data$getSerie(fdays[i]+1)[1:horizon]
213 prediction = prediction - mean(prediction) #predict centered serie (artificial...)
214 private$.params$weights <- similarities
215 private$.params$indices <- fdays
216 private$.params$window <-
219 else if (simtype=="exo")