1 #' @include Forecaster.R
3 #' @title Neighbors Forecaster
5 #' @description Predict tomorrow as a weighted combination of "futures of the past" days.
6 #' Inherits \code{\link{Forecaster}}
7 NeighborsForecaster = setRefClass(
8 Class = "NeighborsForecaster",
9 contains = "Forecaster",
12 initialize = function(...)
16 predictShape = function(today, memory, horizon, ...)
18 # (re)initialize computed parameters
19 params <<- list("weights"=NA, "indices"=NA, "window"=NA)
21 first_day = max(today - memory, 1)
22 # The first day is generally not complete:
23 if (length(data$getCenteredSerie(1)) < length(data$getCenteredSerie(2)))
26 # Predict only on (almost) non-NAs days
27 nas_in_serie = is.na(data$getSerie(today))
28 if (any(nas_in_serie))
30 #TODO: better define "repairing" conditions (and method)
31 if (sum(nas_in_serie) >= length(nas_in_serie) / 2)
33 for (i in seq_along(nas_in_serie))
39 while (left>=1 && nas_in_serie[left])
43 while (right<=length(nas_in_serie) && nas_in_serie[right])
45 #HACK: modify by-reference Data object...
46 data$data[[today]]$serie[i] <<-
47 if (left==0) data$data[[today]]$serie[right]
48 else if (right==0) data$data[[today]]$serie[left]
49 else (data$data[[today]]$serie[left] + data$data[[today]]$serie[right]) / 2.
54 # Determine indices of no-NAs days followed by no-NAs tomorrows
56 for (i in first_day:(today-1))
58 if ( !any(is.na(data$getSerie(i)) | is.na(data$getSerie(i+1))) )
59 fdays_indices = c(fdays_indices, i)
63 # Similarity computed with exogenous variables ? endogenous ? both ? ("exo","endo","mix")
64 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "mix")
65 simthresh = ifelse(hasArg("simthresh"), list(...)$simthresh, 0.)
66 kernel = ifelse(hasArg("kernel"), list(...)$kernel, "Gauss") #or "Epan"
67 mix_strategy = ifelse(hasArg("mix_strategy"), list(...)$mix_strategy, "mult") #or "neighb"
68 same_season = ifelse(hasArg("same_season"), list(...)$same_season, FALSE)
70 return (.predictShapeAux(fdays_indices, today, horizon, list(...)$h_window, kernel,
71 simtype, simthresh, mix_strategy, TRUE))
74 # Indices for cross-validation; TODO: 45 = magic number
75 indices = getSimilarDaysIndices(today, limit=45, same_season=same_season)
76 if (tail(indices,1) == 1)
77 indices = head(indices,-1)
79 # Function to optimize h : h |--> sum of prediction errors on last 45 "similar" days
80 errorOnLastNdays = function(h, kernel, simtype)
86 # NOTE: predict only on non-NAs days followed by non-NAs (TODO:)
87 if (!any(is.na(data$getSerie(i)) | is.na(data$getSerie(i+1))))
89 nb_jours = nb_jours + 1
90 # mix_strategy is never used here (simtype != "mix"), therefore left blank
91 prediction = .predictShapeAux(fdays_indices, i, horizon, h, kernel, simtype,
93 if (!is.na(prediction[1]))
94 error = error + mean((data$getCenteredSerie(i+1)[1:horizon] - prediction)^2)
97 return (error / nb_jours)
101 if (simtype != "endo" && !(simtype=="mix" && mix_strategy=="neighb"))
103 h_best_exo = optimize(errorOnLastNdays, interval=c(0,10), kernel=kernel,
104 simtype="exo")$minimum
106 if (simtype != "exo")
108 h_best_endo = optimize(errorOnLastNdays, interval=c(0,10), kernel=kernel,
109 simtype="endo")$minimum
112 if (simtype == "endo")
114 return (.predictShapeAux(fdays_indices, today, horizon, h_best_endo, kernel, "endo",
115 simthresh, "", TRUE))
117 if (simtype == "exo")
119 return (.predictShapeAux(fdays_indices, today, horizon, h_best_exo, kernel, "exo",
120 simthresh, "", TRUE))
122 if (simtype == "mix")
124 return (.predictShapeAux(fdays_indices, today, horizon, c(h_best_endo,h_best_exo),
125 kernel, "mix", simthresh, mix_strategy, TRUE))
128 # Precondition: "today" is full (no NAs)
129 .predictShapeAux = function(fdays_indices, today, horizon, h, kernel, simtype, simthresh,
130 mix_strategy, final_call)
132 dat = data$data #HACK: faster this way...
134 fdays_indices = fdays_indices[fdays_indices < today]
135 # TODO: 3 = magic number
136 if (length(fdays_indices) < 3)
139 if (simtype != "exo")
141 h_endo = ifelse(simtype=="mix", h[1], h)
143 # Distances from last observed day to days in the past
144 distances2 = rep(NA, length(fdays_indices))
145 for (i in seq_along(fdays_indices))
147 delta = dat[[today]]$serie - dat[[ fdays_indices[i] ]]$serie
148 # Require at least half of non-NA common values to compute the distance
149 if (sum(is.na(delta)) <= 0) #length(delta)/2)
150 distances2[i] = mean(delta^2) #, na.rm=TRUE)
153 sd_dist = sd(distances2)
154 if (sd_dist < .Machine$double.eps)
155 sd_dist = 1 #mostly for tests... FIXME:
158 exp(-distances2/(sd_dist*h_endo^2))
160 u = 1 - distances2/(sd_dist*h_endo^2)
166 if (simtype != "endo")
168 h_exo = ifelse(simtype=="mix", h[2], h)
170 M = matrix( nrow=1+length(fdays_indices), ncol=1+length(dat[[today]]$exo) )
171 M[1,] = c( dat[[today]]$level, as.double(dat[[today]]$exo) )
172 for (i in seq_along(fdays_indices))
174 M[i+1,] = c( dat[[ fdays_indices[i] ]]$level,
175 as.double(dat[[ fdays_indices[i] ]]$exo) )
178 sigma = cov(M) #NOTE: robust covariance is way too slow
179 sigma_inv = solve(sigma) #TODO: use pseudo-inverse if needed?
181 # Distances from last observed day to days in the past
182 distances2 = rep(NA, nrow(M)-1)
185 delta = M[1,] - M[i,]
186 distances2[i-1] = delta %*% sigma_inv %*% delta
189 sd_dist = sd(distances2)
191 if (kernel=="Gauss") {
192 exp(-distances2/(sd_dist*h_exo^2))
193 } else { #Epanechnikov
194 u = 1 - distances2/(sd_dist*h_exo^2)
202 if (mix_strategy == "neighb")
204 #Only (60) most similar days according to exogen variables are kept into consideration
205 #TODO: 60 = magic number
206 keep_indices = sort(simils_exo, index.return=TRUE)$ix[1:(min(60,length(simils_exo)))]
207 simils_endo[-keep_indices] = 0.
209 else #mix_strategy == "mult"
210 simils_endo = simils_endo * simils_exo
214 if (simtype != "exo") {
222 max_sim = max(similarities)
223 # Set to 0 all similarities s where s / max_sim < simthresh, but keep at least 60
224 ordering = sort(similarities / max_sim, index.return=TRUE)
225 if (ordering[60] < simthresh)
227 similarities[ ordering$ix[ - (1:60) ] ] = 0.
231 while (limit < length(similarities) && ordering[limit] >= simthresh)
233 similarities[ ordering$ix[ - 1:limit] ] = 0.
237 prediction = rep(0, horizon)
238 for (i in seq_along(fdays_indices))
239 prediction = prediction + similarities[i] * dat[[ fdays_indices[i]+1 ]]$serie[1:horizon]
240 prediction = prediction / sum(similarities, na.rm=TRUE)
244 params$weights <<- similarities
245 params$indices <<- fdays_indices
247 if (simtype=="endo") {
249 } else if (simtype=="exo") {