X-Git-Url: https://git.auder.net/?a=blobdiff_plain;f=pkg%2FR%2FF_Neighbors.R;h=a3d44a3916cc8b27195ddd693fc35f6dbcceb2b1;hb=546b0cb65870355a2a2c3705c91418570499d3a6;hp=238274bd5f8b1202ab601c8ecea5aad83fc4b578;hpb=98e958cab563866f8e00886b54336018a2e8bc97;p=talweg.git diff --git a/pkg/R/F_Neighbors.R b/pkg/R/F_Neighbors.R index 238274b..a3d44a3 100644 --- a/pkg/R/F_Neighbors.R +++ b/pkg/R/F_Neighbors.R @@ -4,6 +4,7 @@ #' #' Predict tomorrow as a weighted combination of "futures of the past" days. #' Inherits \code{\link{Forecaster}} +#' NeighborsForecaster = R6::R6Class("NeighborsForecaster", inherit = Forecaster, @@ -13,6 +14,10 @@ NeighborsForecaster = R6::R6Class("NeighborsForecaster", # (re)initialize computed parameters private$.params <- list("weights"=NA, "indices"=NA, "window"=NA) + # Do not forecast on days with NAs (TODO: softer condition...) + if (any(is.na(data$getCenteredSerie(today)))) + return (NA) + # Determine indices of no-NAs days followed by no-NAs tomorrows fdays = getNoNA2(data, max(today-memory,1), today-1) @@ -96,17 +101,22 @@ NeighborsForecaster = R6::R6Class("NeighborsForecaster", { delta = data$getCenteredSerie(today) - data$getCenteredSerie(fdays[i]) # Require at least half of non-NA common values to compute the distance - if (sum(is.na(delta)) <= 0) #length(delta)/2) - distances2[i] = mean(delta^2) #, na.rm=TRUE) + if ( !any( is.na(delta) ) ) + distances2[i] = mean(delta^2) } sd_dist = sd(distances2) if (sd_dist < .Machine$double.eps) + { + warning("All computed distances are very close: stdev too small") sd_dist = 1 #mostly for tests... FIXME: + } simils_endo = if (kernel=="Gauss") exp(-distances2/(sd_dist*h_endo^2)) - else { #Epanechnikov + else + { + # Epanechnikov u = 1 - distances2/(sd_dist*h_endo^2) u[abs(u)>1] = 0. u @@ -134,10 +144,17 @@ NeighborsForecaster = R6::R6Class("NeighborsForecaster", } sd_dist = sd(distances2) + if (sd_dist < .Machine$double.eps) + { + warning("All computed distances are very close: stdev too small") + sd_dist = 1 #mostly for tests... FIXME: + } simils_exo = if (kernel=="Gauss") exp(-distances2/(sd_dist*h_exo^2)) - else { #Epanechnikov + else + { + # Epanechnikov u = 1 - distances2/(sd_dist*h_exo^2) u[abs(u)>1] = 0. u @@ -162,13 +179,12 @@ NeighborsForecaster = R6::R6Class("NeighborsForecaster", private$.params$weights <- similarities private$.params$indices <- fdays private$.params$window <- - if (simtype=="endo") { + if (simtype=="endo") h_endo - } else if (simtype=="exo") { + else if (simtype=="exo") h_exo - } else { #mix + else #mix c(h_endo,h_exo) - } } return (prediction)