From 7e3408704b76421e54e0dfdb8b23fc3636814058 Mon Sep 17 00:00:00 2001 From: Mike Tokic Date: Wed, 27 Sep 2023 10:55:06 -0700 Subject: [PATCH] fix box-cox transformation for time series that only have 1-2 non-zero target values --- DESCRIPTION | 2 +- R/prep_data.R | 2 +- R/train_models.R | 27 +++++++++++++++++---------- 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index ba2bca0e..23d815af 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: finnts Title: Microsoft Finance Time Series Forecasting Framework -Version: 0.3.0.9004 +Version: 0.3.0.9005 Authors@R: c(person(given = "Mike", family = "Tokic", diff --git a/R/prep_data.R b/R/prep_data.R index 9f464f90..3d3533d0 100644 --- a/R/prep_data.R +++ b/R/prep_data.R @@ -1035,7 +1035,7 @@ apply_box_cox <- function(df) { diff_info <- tibble::tibble( Combo = unique(df$Combo), - Box_Cox_Lambda = NULL + Box_Cox_Lambda = NA ) for (column_name in names(df)) { diff --git a/R/train_models.R b/R/train_models.R index f198702e..230bc934 100644 --- a/R/train_models.R +++ b/R/train_models.R @@ -564,22 +564,29 @@ train_models <- function(run_info, dplyr::select(Box_Cox_Lambda) %>% dplyr::pull(Box_Cox_Lambda) - final_fcst_return <- x %>% - dplyr::mutate( - Forecast = timetk::box_cox_inv_vec(Forecast, lambda = lambda), - Target = timetk::box_cox_inv_vec(Target, lambda = lambda) - ) + if (!is.na(lambda)) { + final_fcst_return <- x %>% + dplyr::mutate( + Forecast = timetk::box_cox_inv_vec(Forecast, lambda = lambda), + Target = timetk::box_cox_inv_vec(Target, lambda = lambda) + ) + } else { + final_fcst_return <- x + } return(final_fcst_return) }) %>% dplyr::bind_rows() } else { lambda <- filtered_combo_info_tbl$Box_Cox_Lambda - final_fcst <- final_fcst %>% - dplyr::mutate( - Forecast = timetk::box_cox_inv_vec(Forecast, lambda = lambda), - Target = timetk::box_cox_inv_vec(Target, lambda = lambda) - ) + + if (!is.na(lambda)) { + final_fcst <- final_fcst %>% + dplyr::mutate( + Forecast = timetk::box_cox_inv_vec(Forecast, lambda = lambda), + Target = timetk::box_cox_inv_vec(Target, lambda = lambda) + ) + } } }