Nothing
#' Intuitionistic Fuzzy Long Short-Term Memory Network for Time Series
#'
#' Fits an intuitionistic fuzzy long short-term memory (IFLSTM) network to a
#' univariate time series. The lagged values of the series, together with
#' their intuitionistic fuzzy membership and non-membership degrees (from
#' intuitionistic fuzzy c-means clustering), are fed to an LSTM network as a
#' sequence. The lag order (sequence length) and the network
#' hyper-parameters can each be set manually or tuned automatically by grid
#' search. The LSTM is implemented in plain R, so no Python, TensorFlow or
#' other deep-learning library is needed.
#'
#' @details
#' \strong{Model.} The first \code{round(length(Data) * Split)} observations
#' form the training set and the rest the test set. Intuitionistic fuzzy
#' c-means clustering (Chaira, 2011) with \code{Class} clusters is fitted to
#' the training observations only. Non-membership degrees come from the
#' Yager-type generator \eqn{\nu = (1 - \mu^\alpha)^{1/\alpha}}, so the
#' hesitation degree \eqn{\pi = 1 - \mu - \nu} is non-negative for
#' \eqn{0 < \alpha \le 1}; \code{Alpha = 1} gives ordinary fuzzy sets. To
#' predict \eqn{y_t} with lag order \eqn{L}, the network reads the
#' \eqn{L} time steps \eqn{y_{t-L}, \dots, y_{t-1}} (oldest first); at each
#' step the input is the value (min-max scaled with training statistics) and
#' its membership and non-membership degrees in every cluster, i.e.
#' \eqn{1 + 2\,Class} inputs per step. Only past values enter the inputs, so
#' the test-set forecasts use no information from the values being forecast.
#'
#' \strong{Network.} One LSTM layer (Hochreiter and Schmidhuber, 1997) with
#' \code{Units} memory cells (input, forget and output gates, tanh
#' candidate) is followed by a linear output on the last hidden state. The
#' network is trained on the target scaled to [0, 1] by back-propagation
#' through time with the Adam optimiser (Kingma and Ba, 2015), learning rate
#' \code{Learn_Rate}, mini-batches of \code{Batch_Size} sequences, mean
#' squared error loss and gradient-norm clipping at 5, for \code{Epochs}
#' passes over the data. Weights are initialised as in Keras
#' (Glorot-uniform input weights, orthogonal recurrent weights, forget-gate
#' bias 1). Because the result depends on the random initial weights,
#' \code{Repeats} networks can be trained from different starts and their
#' predictions averaged. \code{Learn_Rate}, \code{Batch_Size} and
#' \code{Repeats} are fixed settings used for every model, including during
#' tuning.
#'
#' \strong{Tuning.} \code{Lag_Tuning} and \code{LSTM_Tuning} are set
#' independently:
#' \itemize{
#' \item \code{"manual"}: the single values \code{Lag} and / or
#' \code{Units}, \code{Epochs} are used as given.
#' \item \code{"auto"}: the parameters are tuned by grid search. Each
#' search range is given as \code{c(min, max, step)} and expands to
#' \code{seq(min, max, by = step)}; for example
#' \code{Lag_Range = c(1, 12, 1)} gives the lags 1 to 12 and
#' \code{Units_Range = c(4, 12, 4)} gives 4, 8, 12 units. If \code{max}
#' is not reached exactly by the steps, the last value is the largest
#' one below \code{max}. Use \code{min = max} for a single value.
#' }
#' When both are \code{"auto"} every combination of lag and network
#' parameters is evaluated. The \code{Epochs} values are scored within one
#' training run per lag and number of units (the validation error is
#' recorded after each requested epoch), so tuning \code{Epochs} adds almost
#' no computing time. With \code{Verbose = TRUE} (default) the search prints
#' the values of every parameter, the number of combinations, and a progress
#' bar with the best score so far, the elapsed time and the estimated time
#' remaining.
#'
#' \strong{Validation.} Candidates are compared on the last
#' \code{Val_Split} share of the training set. With \code{"holdout"} the
#' model is fitted on the observations before that block and evaluated on
#' the block. With \code{"tscv"} the block is divided into \code{Folds}
#' consecutive parts and each part is predicted from a model fitted on all
#' earlier observations (expanding window). The clustering and scaling are
#' re-estimated on each fitting window. After tuning, the model is refitted
#' on the whole training set with the best parameters.
#'
#' \strong{Output.} With \code{Verbose = TRUE} a summary of the selected
#' parameters and the accuracy is shown as a message at the end (silence it
#' with \code{Verbose = FALSE} or \code{suppressMessages()}), and the result is
#' returned invisibly; assign it (e.g. \code{Model <- IFLSTM(...)}) to keep
#' it.
#'
#' \strong{Reproducibility.} The clustering, the initial weights and the
#' order of the mini-batches are random, so call \code{set.seed()} before
#' \code{IFLSTM()} to obtain reproducible results.
#'
#' @param Data Numeric time series (vector or \code{ts}) without missing
#' values.
#' @param Class Number of intuitionistic fuzzy clusters (at least 2).
#' @param Split Proportion of the data used for training, strictly between 0
#' and 1.
#' @param Lag_Tuning \code{"auto"} (default) to tune the lag order over
#' \code{Lag_Range}, or \code{"manual"} to use \code{Lag}.
#' @param Lag Lag order (sequence length) used when
#' \code{Lag_Tuning = "manual"} (a single positive integer).
#' @param Lag_Range Lag search range \code{c(min, max, step)} for
#' \code{Lag_Tuning = "auto"} (positive integers). Lags too large for the
#' data are dropped with a warning.
#' @param LSTM_Tuning \code{"auto"} (default) to tune \code{Units} and
#' \code{Epochs}, or \code{"manual"} to use the single values given.
#' @param Units,Epochs Number of LSTM units (memory cells) and number of
#' training epochs, used when \code{LSTM_Tuning = "manual"} (positive
#' integers).
#' @param Units_Range,Epochs_Range Search ranges \code{c(min, max, step)} for
#' \code{LSTM_Tuning = "auto"} (positive integers).
#' @param Learn_Rate Learning rate of the Adam optimiser.
#' @param Batch_Size Number of sequences per mini-batch.
#' @param Repeats Number of networks trained from different random starting
#' weights; their predictions are averaged.
#' @param Validation \code{"holdout"} (default) or \code{"tscv"}
#' (expanding-window time-series cross-validation).
#' @param Val_Split Share of the training set used for validation, strictly
#' between 0 and 1.
#' @param Folds Number of folds for \code{Validation = "tscv"}.
#' @param Metric Criterion minimised during tuning: \code{"RMSE"} (default),
#' \code{"MAE"} or \code{"MAPE"}.
#' @param Forecast_Type \code{"one-step"} (default): every test value is
#' predicted from the observed previous values. \code{"recursive"}: the
#' test period is forecast multi-step ahead, feeding predictions back as
#' lags. The same type is used during validation.
#' @param m Fuzzifier of the clustering (greater than 1).
#' @param Alpha Exponent of the Yager non-membership generator, in (0, 1].
#' @param Max_Iter,Tol Maximum number of iterations and convergence
#' tolerance of the clustering.
#' @param Verbose Logical; show the grid-search progress and the result
#' summary as messages (default \code{TRUE}).
#'
#' @return A list (returned invisibly) with components
#' \describe{
#' \item{\code{Accuracy}}{Matrix of RMSE, MAE and MAPE (\%) for the
#' training and test sets.}
#' \item{\code{Train_Fitted}}{Fitted values for the training targets
#' (the first \code{Lag} training observations have no fitted value).}
#' \item{\code{Test_Prediction}}{Predictions for the test set.}
#' \item{\code{Train_Actual}, \code{Test_Actual}}{The corresponding
#' observed values.}
#' \item{\code{Best_Params}}{List with \code{Lag}, \code{Units} and
#' \code{Epochs} of the final model.}
#' \item{\code{Architecture}}{Time steps, inputs per step, units, number
#' of trainable parameters per network, learning rate, batch size and
#' number of repeats.}
#' \item{\code{Loss}}{Training loss (mean squared error on the scaled
#' target) after each epoch of the final model, averaged over the
#' repeats.}
#' \item{\code{Tuning}}{\code{NULL} when nothing was tuned; otherwise a
#' list with the validation scheme, metric, number of combinations,
#' best validation score, elapsed time and \code{History} (a data frame
#' with the score of every combination).}
#' \item{\code{Networks}}{List of the \code{Repeats} trained networks
#' (weight matrices \code{W}, biases \code{b}, output weights \code{V}
#' and output bias \code{c0}).}
#' \item{\code{Scaling}}{Minimum and maximum of the training data used for
#' the [0, 1] scaling.}
#' \item{\code{IFCM}}{The intuitionistic fuzzy clustering of the training
#' set (centres, membership, non-membership and hesitation degrees).}
#' \item{\code{Settings}}{Other settings used.}
#' }
#'
#' @references
#' Yolcu, O.C. and Yolcu, U. (2023). A novel intuitionistic fuzzy time
#' series prediction model with cascaded structure for financial time
#' series. \emph{Expert Systems with Applications}, 215, 119336.
#' \doi{10.1016/j.eswa.2022.119336}
#'
#' Chaira, T. (2011). A novel intuitionistic fuzzy C means clustering
#' algorithm and its application to medical images. \emph{Applied Soft
#' Computing}, 11(2), 1711--1717.
#'
#' Hochreiter, S. and Schmidhuber, J. (1997). Long short-term memory.
#' \emph{Neural Computation}, 9(8), 1735--1780.
#' \doi{10.1162/neco.1997.9.8.1735}
#'
#' Kingma, D.P. and Ba, J. (2015). Adam: A method for stochastic
#' optimization. \emph{International Conference on Learning
#' Representations (ICLR)}.
#'
#' @examples
#' set.seed(123)
#' dat <- 50 + 10 * sin(2 * pi * (1:120) / 12) + rnorm(120)
#'
#' # Everything manual: lag 12, 8 units, 50 epochs
#' Model1 <- IFLSTM(dat, Class = 3, Split = 0.8,
#' Lag_Tuning = "manual", Lag = 12,
#' LSTM_Tuning = "manual", Units = 8, Epochs = 50)
#' Model1$Accuracy
#'
#' # Manual lag, units and epochs tuned on a very small grid
#' Model2 <- IFLSTM(dat, Class = 3, Split = 0.8,
#' Lag_Tuning = "manual", Lag = 6,
#' Units_Range = c(4, 8, 4), # 4, 8
#' Epochs_Range = c(20, 40, 20), # 20, 40
#' Verbose = FALSE)
#' Model2$Best_Params
#'
#' \donttest{
#' # Lag, units and epochs tuned jointly (small grid)
#' Model3 <- IFLSTM(dat, Class = 3, Split = 0.8,
#' Lag_Range = c(3, 12, 3), # 3, 6, 9, 12
#' Units_Range = c(4, 8, 4), # 4, 8
#' Epochs_Range = c(25, 50, 25), # 25, 50
#' Verbose = FALSE)
#' head(Model3$Tuning$History)
#' plot(Model3$Loss, type = "l", xlab = "Epoch", ylab = "Training loss")
#' }
#'
#' @importFrom stats runif rnorm setNames
#' @export
IFLSTM <- function(Data, Class = 3, Split = 0.8,
Lag_Tuning = c("auto", "manual"),
Lag = 1,
Lag_Range = c(min = 1, max = 12, step = 1),
LSTM_Tuning = c("auto", "manual"),
Units = 8, Epochs = 100,
Units_Range = c(min = 4, max = 12, step = 4),
Epochs_Range = c(min = 50, max = 150, step = 50),
Learn_Rate = 0.01, Batch_Size = 32, Repeats = 1,
Validation = c("holdout", "tscv"),
Val_Split = 0.2, Folds = 3,
Metric = c("RMSE", "MAE", "MAPE"),
Forecast_Type = c("one-step", "recursive"),
m = 2, Alpha = 0.85, Max_Iter = 100, Tol = 1e-5,
Verbose = TRUE) {
call <- match.call()
# ---- argument checks ---------------------------------------------------
Lag_Tuning <- match.arg(Lag_Tuning)
LSTM_Tuning <- match.arg(LSTM_Tuning)
Validation <- match.arg(Validation)
Metric <- match.arg(Metric)
Forecast_Type <- match.arg(Forecast_Type)
if (!is.numeric(Data)) stop("Data must be numeric")
if (anyNA(Data)) stop("Data must not contain missing values")
y <- as.numeric(Data)
n <- length(y)
.is_count <- function(x, min = 1) {
is.numeric(x) && length(x) == 1L && !is.na(x) && x >= min && x == round(x)
}
if (!.is_count(Class, 2)) stop("Class must be an integer >= 2")
Class <- as.integer(Class)
if (!is.numeric(Split) || length(Split) != 1L || Split <= 0 || Split >= 1) {
stop("Split must be between 0 and 1")
}
if (!is.numeric(m) || length(m) != 1L || m <= 1) stop("m must be greater than 1")
if (!is.numeric(Alpha) || length(Alpha) != 1L || Alpha <= 0 || Alpha > 1) {
stop("Alpha must be in (0, 1]")
}
if (!is.numeric(Val_Split) || length(Val_Split) != 1L || Val_Split <= 0 || Val_Split >= 1) {
stop("Val_Split must be between 0 and 1")
}
if (!.is_count(Folds, 1)) stop("Folds must be a positive integer")
if (!is.numeric(Learn_Rate) || length(Learn_Rate) != 1L || is.na(Learn_Rate) ||
Learn_Rate <= 0) {
stop("Learn_Rate must be a single positive number")
}
if (!.is_count(Batch_Size, 1)) stop("Batch_Size must be a positive integer")
if (!.is_count(Repeats, 1)) stop("Repeats must be a positive integer")
if (!is.logical(Verbose) || length(Verbose) != 1L || is.na(Verbose)) {
stop("Verbose must be TRUE or FALSE")
}
ctrl <- list(Learn_Rate = Learn_Rate, Batch_Size = as.integer(Batch_Size),
Repeats = as.integer(Repeats))
ntrain <- as.integer(round(n * Split))
if (ntrain < 1 || ntrain >= n) {
stop("Data is too short: training and test sets must both be non-empty")
}
if (Lag_Tuning == "manual") {
if (!.is_count(Lag, 1)) stop("Lag must be a single positive integer")
Lag <- as.integer(Lag)
} else {
lag_values <- .range_values(Lag_Range, "Lag_Range", integer = TRUE)
}
if (LSTM_Tuning == "manual") {
if (!.is_count(Units, 1)) stop("Units must be a single positive integer")
if (!.is_count(Epochs, 1)) stop("Epochs must be a single positive integer")
Units <- as.integer(Units)
Epochs <- as.integer(Epochs)
} else {
units_values <- .range_values(Units_Range, "Units_Range", integer = TRUE)
epoch_values <- .range_values(Epochs_Range, "Epochs_Range", integer = TRUE)
}
if (Metric == "MAPE" && any(y[seq_len(ntrain)] == 0)) {
stop("Metric = \"MAPE\" cannot be used when the training data contain zeros")
}
tuning_needed <- Lag_Tuning == "auto" || LSTM_Tuning == "auto"
min_rows <- 5L
# ---- grid-search tuning ------------------------------------------------
tuning <- NULL
best <- list(
Lag = if (Lag_Tuning == "manual") Lag else NA_integer_,
Units = Units,
Epochs = Epochs
)
if (tuning_needed) {
folds <- .make_folds(ntrain, Validation, Val_Split, Folds)
first_end <- min(vapply(folds, `[[`, integer(1), "fit_end"))
max_lag <- first_end - min_rows
if (Lag_Tuning == "auto") {
keep <- lag_values[lag_values <= max_lag]
if (length(keep) == 0L) {
stop("The training set is too short for tuning even with lag ",
min(lag_values), "; use more data, a larger Split or a smaller Val_Split")
}
if (length(keep) < length(lag_values)) {
warning("Lags larger than ", max_lag,
" are too long for the validation window and were dropped from Lag_Range")
}
lag_values <- keep
} else if (Lag > max_lag) {
stop("Lag = ", Lag, " is too large for tuning on this training set (maximum ",
max(max_lag, 0), ")")
}
preps <- lapply(folds, function(fo) {
.prepare(y[seq_len(fo$fit_end)], Class, m, Alpha, Max_Iter, Tol)
})
fixed <- list()
if (Lag_Tuning == "manual") fixed$Lag <- Lag
if (LSTM_Tuning == "manual") {
fixed$Units <- Units
fixed$Epochs <- Epochs
}
gv <- list()
if (Lag_Tuning == "auto") gv$Lag <- lag_values
if (LSTM_Tuning == "auto") {
gv$Units <- units_values
gv$Epochs <- epoch_values
}
group_eval <- .make_group_eval(y, folds, preps, ctrl, Metric, Forecast_Type)
header <- function() {
.grid_header(gv, fixed, folds, ntrain, Validation, Metric, ctrl)
}
t0 <- Sys.time()
history <- .grid_search(gv, fixed, group_eval, Verbose, Metric, header)
elapsed <- as.numeric(difftime(Sys.time(), t0, units = "secs"))
if (!any(is.finite(history$Score))) {
stop("Every combination failed during tuning; check the search ranges ",
"or use a smaller Learn_Rate")
}
b <- which.min(history$Score)
for (nm in names(gv)) best[[nm]] <- history[[nm]][b]
for (nm in names(fixed)) best[[nm]] <- fixed[[nm]]
tuning <- list(
Method = "grid",
Validation = Validation,
Metric = Metric,
Combinations = nrow(history),
Best_Score = history$Score[b],
Elapsed_Seconds = elapsed,
History = history
)
}
best$Lag <- as.integer(best$Lag)
best$Units <- as.integer(best$Units)
best$Epochs <- as.integer(best$Epochs)
L <- best$Lag
if (ntrain - L < min_rows) {
stop("Lag = ", L, " leaves fewer than ", min_rows,
" training observations; use a smaller lag or more data")
}
# ---- final model -------------------------------------------------------
prep <- .prepare(y[seq_len(ntrain)], Class, m, Alpha, Max_Iter, Tol)
train_idx <- (L + 1L):ntrain
test_idx <- (ntrain + 1L):n
fit <- .fit_lstm(y, train_idx, L, prep, Units = best$Units,
Epochs = best$Epochs, ctrl = ctrl)
train_fitted <- .predict_lstm(fit$nets, y, train_idx, L, prep, "one-step")
test_pred <- .predict_lstm(fit$nets, y, test_idx, L, prep, Forecast_Type)
acc <- rbind(
"Training set" = .metrics(y[train_idx], train_fitted),
"Test set" = .metrics(y[test_idx], test_pred)
)
d <- .n_step_inputs(Class)
result <- list(
Accuracy = acc,
Train_Fitted = train_fitted,
Test_Prediction = test_pred,
Train_Actual = y[train_idx],
Test_Actual = y[test_idx],
Best_Params = best[c("Lag", "Units", "Epochs")],
Architecture = list(
Time_Steps = L,
Inputs_Per_Step = d,
Units = best$Units,
Parameters = .n_params(d, best$Units),
Learn_Rate = Learn_Rate,
Batch_Size = ctrl$Batch_Size,
Repeats = ctrl$Repeats
),
Loss = Reduce(`+`, fit$loss) / length(fit$loss),
Tuning = tuning,
Networks = fit$nets,
Scaling = c(min = prep$scaling$lo, max = prep$scaling$hi),
IFCM = prep$ifcm,
Settings = list(
Class = Class, Split = Split,
Lag_Tuning = Lag_Tuning, LSTM_Tuning = LSTM_Tuning,
Forecast_Type = Forecast_Type, m = m, Alpha = Alpha,
n_train = ntrain, n_test = n - ntrain
),
Call = call
)
if (Verbose) .show_summary(result)
invisible(result)
}
# Summary shown at the end of IFLSTM() when Verbose = TRUE (internal).
# It is sent as a message, so it can be silenced with suppressMessages().
.show_summary <- function(x) {
s <- x$Settings
a <- x$Architecture
bp <- x$Best_Params
lines <- c(
"Intuitionistic Fuzzy Long Short-Term Memory Network (IFLSTM)",
"",
paste0("Clusters: ", s$Class, " Train/Test: ", s$n_train, " / ", s$n_test,
" Forecast: ", s$Forecast_Type),
sprintf("Network: %d time steps x %d inputs -> LSTM(%d) -> 1 (%d parameters)%s",
a$Time_Steps, a$Inputs_Per_Step, a$Units, a$Parameters,
if (a$Repeats == 1L) "" else sprintf(", %d networks averaged", a$Repeats)),
sprintf("Training: Adam, learning rate %s, batch size %d, final loss %s",
format(a$Learn_Rate, digits = 4), a$Batch_Size,
format(signif(utils::tail(x$Loss, 1), 4))),
paste0("Lag tuning: ", s$Lag_Tuning, " LSTM tuning: ", s$LSTM_Tuning)
)
if (!is.null(x$Tuning)) {
lines <- c(lines, paste0(
"Grid search: ", format(x$Tuning$Combinations, big.mark = ","),
" combinations Validation: ", x$Tuning$Validation, " ",
x$Tuning$Metric, " = ", format(x$Tuning$Best_Score, digits = 5)))
}
lines <- c(
lines, "", "Selected parameters:",
paste0(" Lag = ", bp$Lag),
paste0(" Units = ", bp$Units),
paste0(" Epochs = ", bp$Epochs),
"", "Accuracy:",
utils::capture.output(print(round(x$Accuracy, 4)))
)
message(paste(lines, collapse = "\n"))
invisible(NULL)
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.