tests/testthat/test-IFLSTM.R

sim <- function(n = 100, seed = 1) {
  set.seed(seed)
  50 + 10 * sin(2 * pi * seq_len(n) / 12) + rnorm(n)
}

# small, fast networks for the tests
fast <- list(Units_Range = c(3, 3, 0), Epochs_Range = c(10, 10, 0))

# ---- exports ---------------------------------------------------------------

test_that("IFLSTM is the only exported function and no print method is registered", {
  expect_identical(getNamespaceExports("IFLSTM"), "IFLSTM")
  expect_null(getS3method("print", "IFLSTM", optional = TRUE))
})

# ---- LSTM core -------------------------------------------------------------

test_that("analytic gradients match numerical gradients", {
  set.seed(1)
  n <- 6; d <- 3; H <- 4; Tn <- 4
  X <- lapply(seq_len(Tn), function(t) matrix(rnorm(n * d), n, d))
  y <- rnorm(n)
  par <- IFLSTM:::.lstm_init(d, H)
  par$b <- rnorm(length(par$b))
  par$c0 <- 0.2
  fw <- IFLSTM:::.lstm_forward(par, X, keep = TRUE)
  g <- IFLSTM:::.lstm_backward(par, X, y, fw)
  worst <- 0
  for (nm in names(par)) for (j in seq_along(par[[nm]])) {
    p1 <- par; p2 <- par; e <- 1e-6
    p1[[nm]][j] <- p1[[nm]][j] + e
    p2[[nm]][j] <- p2[[nm]][j] - e
    num <- (IFLSTM:::.lstm_loss(p1, X, y) - IFLSTM:::.lstm_loss(p2, X, y)) / (2 * e)
    worst <- max(worst, abs(num - g[[nm]][j]) / max(1e-8, abs(num) + abs(g[[nm]][j])))
  }
  expect_lt(worst, 1e-5)
})

test_that("initialisation follows the Keras conventions", {
  set.seed(2)
  par <- IFLSTM:::.lstm_init(5, 4)
  expect_equal(dim(par$W), c(5 + 4, 16))
  expect_equal(par$b[5:8], rep(1, 4))                 # forget-gate bias
  expect_equal(par$b[-(5:8)], rep(0, 12))
  R1 <- par$W[6:9, 1:4]
  expect_equal(crossprod(R1), diag(4), tolerance = 1e-8)  # orthogonal recurrent
  expect_equal(IFLSTM:::.n_params(5, 4), length(par$W) + length(par$b) + length(par$V) + 1)
})

test_that("training reduces the loss on a learnable sequence task", {
  set.seed(3)
  s <- sin(2 * pi * (1:150) / 12)
  s <- (s - min(s)) / (max(s) - min(s))
  idx <- 7:150
  X <- lapply(6:1, function(k) matrix(s[idx - k], ncol = 1))
  fit <- IFLSTM:::.lstm_train(X, s[idx], H = 4, epochs = 60, lr = 0.02, batch = 32)
  expect_length(fit$loss, 60)
  expect_lt(fit$loss[60], fit$loss[1] / 10)
  expect_lt(IFLSTM:::.lstm_loss(fit$par, X, s[idx]), 0.005)
})

test_that("scoring an epoch inside a longer run equals training for that many epochs", {
  set.seed(4)
  y <- sim(80)
  prep <- IFLSTM:::.prepare(y[1:60], 2, 2, 0.85, 100, 1e-5)
  ctrl <- list(Learn_Rate = 0.01, Batch_Size = 16L, Repeats = 1L)
  set.seed(10)
  long <- IFLSTM:::.fit_lstm(y, 4:60, 3, prep, Units = 3, Epochs = 20, ctrl = ctrl,
                             eval_idx = 61:70, eval_epochs = c(10L, 20L))
  set.seed(10)
  short <- IFLSTM:::.fit_lstm(y, 4:60, 3, prep, Units = 3, Epochs = 10, ctrl = ctrl)
  expect_equal(long$eval[, 1], IFLSTM:::.predict_lstm(short$nets, y, 61:70, 3, prep))
  expect_false(isTRUE(all.equal(long$eval[, 1], long$eval[, 2])))
})

# ---- input validation ------------------------------------------------------

test_that("IFLSTM validates its inputs", {
  x <- sim()
  expect_error(IFLSTM(letters[1:20]), "Data must be numeric")
  expect_error(IFLSTM(c(x[1:49], NA)), "missing values")
  expect_error(IFLSTM(x, Class = 1), "Class must be")
  expect_error(IFLSTM(x, Split = 1), "Split must be between 0 and 1")
  expect_error(IFLSTM(x, Split = 0), "Split must be between 0 and 1")
  expect_error(IFLSTM(c(1, 2, 3), Class = 2, Split = 0.99), "too short")
  expect_error(IFLSTM(x, Lag_Tuning = "manual", Lag = 0), "Lag must be")
  expect_error(IFLSTM(x, Lag_Tuning = "manual", Lag = 2.5), "Lag must be")
  expect_error(IFLSTM(x, LSTM_Tuning = "manual", Units = 0), "Units must be")
  expect_error(IFLSTM(x, LSTM_Tuning = "manual", Epochs = 1.5), "Epochs must be")
  expect_error(IFLSTM(x, Learn_Rate = 0), "Learn_Rate must be")
  expect_error(IFLSTM(x, Batch_Size = 0), "Batch_Size must be")
  expect_error(IFLSTM(x, Repeats = 0), "Repeats must be")
  expect_error(IFLSTM(x, Alpha = 1.5), "Alpha must be")
  expect_error(IFLSTM(x, m = 1), "m must be")
  expect_error(IFLSTM(c(0, x), Metric = "MAPE"), "zeros")
  expect_error(IFLSTM(x, Verbose = NA), "Verbose")
})

test_that("search ranges must be c(min, max, step)", {
  x <- sim()
  expect_error(IFLSTM(x, Lag_Range = 1:12), "c\\(min, max, step\\)")
  expect_error(IFLSTM(x, Lag_Range = c(0, 5, 1)), "positive integers")
  expect_error(IFLSTM(x, Units_Range = c(2, 8, 0.5)), "positive integers")
  expect_error(IFLSTM(x, Units_Range = c(8, 2, 2)), "max must be")
  expect_error(IFLSTM(x, Epochs_Range = c(50, 150, 0)), "step must be positive")
})

test_that("ranges expand like seq(min, max, by = step)", {
  rv <- IFLSTM:::.range_values
  expect_equal(rv(c(1, 12, 1), "L", integer = TRUE), 1:12)
  expect_equal(rv(c(4, 12, 4), "U", integer = TRUE), c(4L, 8L, 12L))
  expect_equal(rv(c(50, 120, 50), "E", integer = TRUE), c(50L, 100L))   # max not hit
  expect_equal(rv(c(5, 5, 0), "U", integer = TRUE), 5L)
  expect_equal(rv(c(step = 2, min = 1, max = 5), "U", integer = TRUE), c(1L, 3L, 5L))
})

# ---- clustering and inputs -------------------------------------------------

test_that("IFCM returns valid intuitionistic fuzzy degrees", {
  set.seed(42)
  res <- IFLSTM:::.ifcm(rnorm(60, 60, 10), Class = 3, alpha = 0.85)
  expect_equal(unname(rowSums(res$membership)), rep(1, 60), tolerance = 1e-8)
  expect_true(all(res$hesitation >= -1e-12))
  expect_true(any(res$hesitation > 1e-3))
  expect_false(is.unsorted(res$centers))
  expect_true(res$converged)
})

test_that("sequence inputs are ordered oldest first and use only past values", {
  set.seed(9)
  y <- rnorm(40, 10)
  prep <- IFLSTM:::.prepare(y[1:30], 2, 2, 0.85, 100, 1e-5)
  X <- IFLSTM:::.seq_inputs(y, 31:35, 3, prep)
  expect_length(X, 3)
  expect_equal(dim(X[[1]]), c(5L, 1L + 2L * 2L))
  sc <- function(v) (v - min(y[1:30])) / (max(y[1:30]) - min(y[1:30]))
  expect_equal(X[[1]][, "Value"], sc(y[28:32]))       # lag 3 first
  expect_equal(X[[3]][, "Value"], sc(y[30:34]))       # lag 1 last
  y2 <- y
  y2[31:35] <- 999
  X2 <- IFLSTM:::.seq_inputs(y2, 31, 3, prep)
  expect_equal(lapply(X, function(m) m[1, ]), lapply(X2, function(m) m[1, ]))
})

# ---- model fitting ---------------------------------------------------------

test_that("fully manual model: shapes, invisible return, silent when Verbose = FALSE", {
  x <- sim(100)
  set.seed(7)
  expect_silent(
    res <- IFLSTM(x, Class = 2, Split = 0.8,
                  Lag_Tuning = "manual", Lag = 4,
                  LSTM_Tuning = "manual", Units = 3, Epochs = 15,
                  Repeats = 2, Verbose = FALSE)
  )
  expect_type(res, "list")
  expect_null(attr(res, "class"))
  expect_null(res$Tuning)
  expect_length(res$Train_Fitted, 80 - 4)
  expect_length(res$Test_Prediction, 20)
  expect_equal(res$Test_Actual, x[81:100])
  expect_true(all(is.finite(res$Test_Prediction)))
  expect_equal(dim(res$Accuracy), c(2L, 3L))
  expect_equal(res$Best_Params, list(Lag = 4L, Units = 3L, Epochs = 15L))
  expect_length(res$Networks, 2)
  expect_length(res$Loss, 15)
  expect_equal(res$Architecture$Inputs_Per_Step, 5L)
  expect_equal(res$Architecture$Parameters, IFLSTM:::.n_params(5L, 3L))

  expect_invisible(IFLSTM(x, Class = 2, Lag_Tuning = "manual", Lag = 2,
                          LSTM_Tuning = "manual", Units = 2, Epochs = 3,
                          Verbose = FALSE))
})

test_that("the summary is shown as a message when Verbose = TRUE", {
  x <- sim(100)
  set.seed(8)
  msgs <- testthat::capture_messages(
    IFLSTM(x, Class = 2, Lag_Tuning = "manual", Lag = 3,
           LSTM_Tuning = "manual", Units = 2, Epochs = 5)
  )
  txt <- paste(msgs, collapse = "")
  expect_match(txt, "Intuitionistic Fuzzy Long Short-Term Memory Network")
  expect_match(txt, "3 time steps x 5 inputs -> LSTM\\(2\\)")
  expect_match(txt, "Selected parameters")
  expect_match(txt, "Test set")
})

test_that("grid search tunes lag, units and epochs jointly", {
  x <- sim(100)
  set.seed(2)
  res <- IFLSTM(x, Class = 2,
                Lag_Range = c(2, 10, 4),          # 2, 6, 10
                Units_Range = c(2, 4, 2),         # 2, 4
                Epochs_Range = c(5, 15, 5),       # 5, 10, 15
                Verbose = FALSE)
  h <- res$Tuning$History
  expect_equal(nrow(h), 3 * 2 * 3)
  expect_equal(res$Tuning$Combinations, 18)
  expect_true(all(is.finite(h$Score)))
  expect_equal(sort(unique(h$Epochs)), c(5L, 10L, 15L))
  expect_equal(res$Tuning$Best_Score, min(h$Score))
  b <- h[which.min(h$Score), ]
  expect_equal(res$Best_Params$Lag, as.integer(b$Lag))
  expect_equal(res$Best_Params$Units, as.integer(b$Units))
  expect_equal(res$Best_Params$Epochs, as.integer(b$Epochs))
})

test_that("the progress display shows the grid and the number of combinations", {
  x <- sim(100)
  set.seed(2)
  msgs <- testthat::capture_messages(
    res <- IFLSTM(x, Class = 2, Lag_Range = c(1, 3, 1),
                  Units_Range = c(2, 2, 0), Epochs_Range = c(5, 10, 5))
  )
  txt <- paste(msgs, collapse = "")
  expect_match(txt, "IFLSTM grid search")
  expect_match(txt, "3 x 1 x 2 = 6 combinations")
  expect_match(txt, "1 network per fit")
  expect_match(txt, "scored within one training run")
  expect_match(txt, "6/6")
  expect_match(txt, "100%")
  expect_match(txt, "Done: 6 combinations")
  # messages can be silenced and nothing goes to standard output
  expect_silent(suppressMessages(
    IFLSTM(x, Class = 2, Lag_Range = c(1, 2, 1),
           Units_Range = c(2, 2, 0), Epochs_Range = c(5, 5, 0))))
})

test_that("manual lag with tuned network, and tuned lag with manual network", {
  x <- sim(100)
  set.seed(3)
  r1 <- IFLSTM(x, Class = 2, Lag_Tuning = "manual", Lag = 12,
               Units_Range = c(2, 3, 1), Epochs_Range = c(5, 5, 0), Verbose = FALSE)
  expect_equal(r1$Best_Params$Lag, 12L)
  expect_false("Lag" %in% names(r1$Tuning$History))

  r2 <- IFLSTM(x, Class = 2, LSTM_Tuning = "manual", Units = 3, Epochs = 8,
               Lag_Range = c(1, 4, 1), Verbose = FALSE)
  expect_equal(r2$Best_Params$Units, 3L)
  expect_equal(r2$Best_Params$Epochs, 8L)
  expect_equal(names(r2$Tuning$History), c("Combination", "Lag", "Score"))
})

test_that("results are reproducible after set.seed()", {
  skip_on_cran()
  x <- sim(90)
  args <- c(list(Data = x, Class = 2, Lag_Range = c(1, 4, 1), Verbose = FALSE), fast)
  set.seed(99)
  r1 <- do.call(IFLSTM, args)
  set.seed(99)
  r2 <- do.call(IFLSTM, args)
  expect_equal(r1$Test_Prediction, r2$Test_Prediction)
  expect_equal(r1$Tuning$History, r2$Tuning$History)
})

test_that("time-series cross-validation and recursive forecasts", {
  skip_on_cran()
  x <- sim(100)
  set.seed(5)
  res <- do.call(IFLSTM, c(list(Data = x, Class = 2, Validation = "tscv", Folds = 3,
                                Forecast_Type = "recursive",
                                Lag_Range = c(2, 12, 10), Verbose = FALSE), fast))
  expect_length(res$Test_Prediction, 20)
  expect_true(all(is.finite(res$Test_Prediction)))
  expect_equal(res$Tuning$Validation, "tscv")
})

test_that("too long lags are dropped with a warning", {
  x <- sim(40)
  set.seed(6)
  expect_warning(
    res <- IFLSTM(x, Class = 2, LSTM_Tuning = "manual", Units = 2, Epochs = 5,
                  Lag_Range = c(2, 30, 28), Verbose = FALSE),
    "dropped"
  )
  expect_equal(res$Best_Params$Lag, 2L)
})

Try the IFLSTM package in your browser

Any scripts or data that you put into this service are public.

IFLSTM documentation built on Nov. 25, 2026, 5:07 p.m.