1 #' Neighbors Forecaster
3 #' Predict tomorrow as a weighted combination of "futures of the past" days.
4 #' Inherits \code{\link{Forecaster}}
6 NeighborsForecaster = R6::R6Class("NeighborsForecaster",
10 predictShape = function(data, today, memory, horizon, ...)
12 # (re)initialize computed parameters
13 private$.params <- list("weights"=NA, "indices"=NA, "window"=NA)
15 # Do not forecast on days with NAs (TODO: softer condition...)
16 if (any(is.na(data$getCenteredSerie(today))))
19 # Determine indices of no-NAs days followed by no-NAs tomorrows
20 fdays = getNoNA2(data, max(today-memory,1), today-1)
23 local = ifelse(hasArg("local"), list(...)$local, TRUE) #same level + season?
24 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "none") #or "endo", or "exo"
27 return ( private$.predictShapeAux(data,
28 fdays, today, horizon, local, list(...)$window, simtype, TRUE) )
31 # Indices of similar days for cross-validation; TODO: 20 = magic number
32 cv_days = getSimilarDaysIndices(today, data, limit=20, same_season=FALSE,
35 # Optimize h : h |--> sum of prediction errors on last N "similar" days
36 errorOnLastNdays = function(window, simtype)
40 for (i in seq_along(cv_days))
42 # mix_strategy is never used here (simtype != "mix"), therefore left blank
43 prediction = private$.predictShapeAux(data, fdays, cv_days[i], horizon, local,
44 window, simtype, FALSE)
45 if (!is.na(prediction[1]))
47 nb_jours = nb_jours + 1
49 mean((data$getSerie(cv_days[i]+1)[1:horizon] - prediction)^2)
52 return (error / nb_jours)
55 # TODO: 7 == magic number
56 if (simtype=="endo" || simtype=="mix")
58 best_window_endo = optimize(
59 errorOnLastNdays, c(0,7), simtype="endo")$minimum
61 if (simtype=="exo" || simtype=="mix")
63 best_window_exo = optimize(
64 errorOnLastNdays, c(0,7), simtype="exo")$minimum
68 if (simtype == "endo")
70 else if (simtype == "exo")
72 else if (simtype == "mix")
73 c(best_window_endo,best_window_exo)
74 else #none: value doesn't matter
77 return(private$.predictShapeAux(data, fdays, today, horizon, local,
78 best_window, simtype, TRUE))
82 # Precondition: "today" is full (no NAs)
83 .predictShapeAux = function(data, fdays, today, horizon, local, window, simtype,
86 fdays_cut = fdays[ fdays < today ]
87 if (length(fdays_cut) <= 1)
92 # Neighbors: days in "same season"; TODO: 60 == magic number...
93 fdays = getSimilarDaysIndices(today, data, limit=60, same_season=TRUE,
95 if (length(fdays) <= 1)
97 levelToday = data$getLevel(today)
98 distances = sapply(fdays, function(i) abs(data$getLevel(i)-levelToday))
99 #TODO: 2, 10, 3, 12 magic numbers here...
101 min_neighbs = min(10,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
116 sort(distances[same_pollution],index.return=TRUE)$ix[1:max_neighbs] ]
118 if (length(fdays) == 1) #the other extreme...
122 private$.params$weights <- 1
123 private$.params$indices <- fdays
124 private$.params$window <- 1
126 return ( data$getSerie(fdays[1])[1:horizon] )
130 fdays = fdays_cut #no conditioning
132 if (simtype == "endo" || simtype == "mix")
134 # Compute endogen similarities using given window
135 window_endo = ifelse(simtype=="mix", window[1], window)
137 # Distances from last observed day to days in the past
138 serieToday = data$getSerie(today)
139 distances2 = sapply(fdays, function(i) {
140 delta = serieToday - data$getSerie(i)
144 sd_dist = sd(distances2)
145 if (sd_dist < .25 * sqrt(.Machine$double.eps))
147 # warning("All computed distances are very close: stdev too small")
148 sd_dist = 1 #mostly for tests... FIXME:
150 simils_endo = exp(-distances2/(sd_dist*window_endo^2))
153 if (simtype == "exo" || simtype == "mix")
155 # Compute exogen similarities using given window
156 window_exo = ifelse(simtype=="mix", window[2], window)
158 M = matrix( nrow=1+length(fdays), ncol=1+length(data$getExo(today)) )
159 M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
160 for (i in seq_along(fdays))
161 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
163 sigma = cov(M) #NOTE: robust covariance is way too slow
164 # TODO: 10 == magic number; more robust way == det, or always ginv()
166 if (length(fdays) > 10)
171 # Distances from last observed day to days in the past
172 distances2 = sapply(seq_along(fdays), function(i) {
173 delta = M[1,] - M[i+1,]
174 delta %*% sigma_inv %*% delta
177 sd_dist = sd(distances2)
178 if (sd_dist < .25 * sqrt(.Machine$double.eps))
180 # warning("All computed distances are very close: stdev too small")
181 sd_dist = 1 #mostly for tests... FIXME:
183 simils_exo = exp(-distances2/(sd_dist*window_exo^2))
187 if (simtype == "exo")
189 else if (simtype == "endo")
191 else if (simtype == "mix")
192 simils_endo * simils_exo
194 rep(1, length(fdays))
195 similarities = similarities / sum(similarities)
197 prediction = rep(0, horizon)
198 for (i in seq_along(fdays))
199 prediction = prediction + similarities[i] * data$getSerie(fdays[i]+1)[1:horizon]
203 private$.params$weights <- similarities
204 private$.params$indices <- fdays
205 private$.params$window <-
208 else if (simtype=="exo")
210 else if (simtype=="mix")
211 c(window_endo,window_exo)