1 #' @include Forecaster.R
3 #' Neighbors Forecaster
5 #' Predict tomorrow as a weighted combination of "futures of the past" days.
6 #' Inherits \code{\link{Forecaster}}
8 NeighborsForecaster = R6::R6Class("NeighborsForecaster",
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 local = ifelse(hasArg("local"), list(...)$local, TRUE) #same level + season?
26 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "none") #or "endo", or "exo"
29 return ( private$.predictShapeAux(data,
30 fdays, today, horizon, local, list(...)$window, 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,
37 # Optimize h : h |--> sum of prediction errors on last N "similar" days
38 errorOnLastNdays = function(window, simtype)
42 for (i in seq_along(cv_days))
44 # mix_strategy is never used here (simtype != "mix"), therefore left blank
45 prediction = private$.predictShapeAux(data, fdays, cv_days[i], horizon, local,
46 window, simtype, FALSE)
47 if (!is.na(prediction[1]))
49 nb_jours = nb_jours + 1
51 mean((data$getSerie(cv_days[i]+1)[1:horizon] - prediction)^2)
54 return (error / nb_jours)
57 # TODO: 7 == magic number
58 if (simtype != "endo")
60 best_window_exo = optimize(
61 errorOnLastNdays, c(0,7), simtype="exo")$minimum
65 best_window_endo = optimize(
66 errorOnLastNdays, c(0,7), simtype="endo")$minimum
69 if (simtype == "endo")
71 return (private$.predictShapeAux(data, fdays, today, horizon, local,
72 best_window_endo, "endo", TRUE))
76 return (private$.predictShapeAux(data, fdays, today, horizon, local,
77 best_window_exo, "exo", TRUE))
81 return(private$.predictShapeAux(data, fdays, today, horizon, local,
82 c(best_window_endo,best_window_exo), "mix", TRUE))
87 # Precondition: "today" is full (no NAs)
88 .predictShapeAux = function(data, fdays, today, horizon, local, window, simtype,
91 fdays_cut = fdays[ fdays < today ]
92 if (length(fdays_cut) <= 1)
97 # Neighbors: days in "same season"; TODO: 60 == magic number...
98 fdays = getSimilarDaysIndices(today, data, limit=60, same_season=TRUE,
100 if (length(fdays) <= 1)
102 levelToday = data$getLevel(today)
103 distances = sapply(fdays, function(i) abs(data$getLevel(i)-levelToday))
104 #TODO: 2, 10, 3, 12 magic numbers here...
106 min_neighbs = min(10,length(fdays))
109 same_pollution = (distances <= dist_thresh)
110 nb_neighbs = sum(same_pollution)
111 if (nb_neighbs >= min_neighbs) #will eventually happen
113 dist_thresh = dist_thresh + 3
115 fdays = fdays[same_pollution]
117 if (nb_neighbs > max_neighbs)
119 # Keep only max_neighbs closest neighbors
121 sort(distances[same_pollution],index.return=TRUE)$ix[1:max_neighbs] ]
123 if (length(fdays) == 1) #the other extreme...
127 private$.params$weights <- 1
128 private$.params$indices <- fdays
129 private$.params$window <- 1
131 return ( data$getSerie(fdays[1])[1:horizon] ) #what else?!
135 fdays = fdays_cut #no conditioning
137 if (simtype == "endo" || simtype == "mix")
139 # Compute endogen similarities using given window
140 window_endo = ifelse(simtype=="mix", window[1], window)
142 # Distances from last observed day to days in the past
143 serieToday = data$getSerie(today)
144 distances2 = sapply(fdays, function(i) {
145 delta = serieToday - data$getSerie(i)
149 sd_dist = sd(distances2)
150 if (sd_dist < .25 * sqrt(.Machine$double.eps))
152 # warning("All computed distances are very close: stdev too small")
153 sd_dist = 1 #mostly for tests... FIXME:
155 simils_endo = exp(-distances2/(sd_dist*window_endo^2))
158 if (simtype == "exo" || simtype == "mix")
160 # Compute exogen similarities using given window
161 window_exo = ifelse(simtype=="mix", window[2], window)
163 M = matrix( nrow=1+length(fdays), ncol=1+length(data$getExo(today)) )
164 M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
165 for (i in seq_along(fdays))
166 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
168 sigma = cov(M) #NOTE: robust covariance is way too slow
169 # TODO: 10 == magic number; more robust way == det, or always ginv()
171 if (length(fdays) > 10)
176 # Distances from last observed day to days in the past
177 distances2 = sapply(seq_along(fdays), function(i) {
178 delta = M[1,] - M[i+1,]
179 delta %*% sigma_inv %*% delta
182 sd_dist = sd(distances2)
183 if (sd_dist < .25 * sqrt(.Machine$double.eps))
185 # warning("All computed distances are very close: stdev too small")
186 sd_dist = 1 #mostly for tests... FIXME:
188 simils_exo = exp(-distances2/(sd_dist*window_exo^2))
192 if (simtype == "exo")
194 else if (simtype == "endo")
196 else if (simtype == "mix")
197 simils_endo * simils_exo
199 rep(1, length(fdays))
200 similarities = similarities / sum(similarities)
202 prediction = rep(0, horizon)
203 for (i in seq_along(fdays))
204 prediction = prediction + similarities[i] * data$getSerie(fdays[i]+1)[1:horizon]
208 private$.params$weights <- similarities
209 private$.params$indices <- fdays
210 private$.params$window <-
213 else if (simtype=="exo")
216 c(window_endo,window_exo)