% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/cv_estimators.R
\name{werm_least_squares_cv}
\alias{werm_least_squares_cv}
\title{Fit a WERM changepoint model with squared loss and CV selection}
\usage{
werm_least_squares_cv(
  X,
  y,
  max_num_chgpts,
  delta = 1L,
  search_method = "efficient",
  cv = 5L,
  fit_intercept = TRUE,
  use_base_loss_for_cv = FALSE,
  penalty = "none",
  alpha = 0
)
}
\arguments{
\item{X}{Numeric matrix of shape \verb{(n, p)}. Observations must be in order.}

\item{y}{Numeric vector of length \code{n}. Ordered responses.}

\item{max_num_chgpts}{Integer. Upper bound of the CV search grid.}

\item{delta}{Integer. Minimum gap between candidate changepoints.
Default \code{1}.}

\item{search_method}{Character. \code{"efficient"} (default) or \code{"brute_force"}.}

\item{cv}{Integer. Number of interleaved folds. Default \code{5}.}

\item{fit_intercept}{Logical. Default \code{TRUE}.}

\item{use_base_loss_for_cv}{Logical. If \code{TRUE}, uses squared loss for CV
segment fits and scoring instead of the default absolute error.
Default \code{FALSE}.}

\item{penalty}{Character. Passed to the inner fixed model. Default \code{"none"}.}

\item{alpha}{Numeric. Penalty strength. Default \code{0}.}
}
\value{
An object of class \code{c("werm_least_squares_cv", "werm_fit")} with all
elements from \code{\link[=werm_least_squares]{werm_least_squares()}} plus:
\describe{
\item{\code{best_num_chgpts}}{Integer. CV-selected number of changepoints.}
\item{\code{best_score}}{Numeric. Mean held-out score for the best model.}
\item{\code{cv_results}}{Data frame with columns \code{num_chgpts} and
\code{mean_test_score}.}
\item{\code{num_chgpts_grid}}{Integer vector. Full CV search grid.}
\item{\code{segment_bounds}}{List of integer pairs \verb{[start, stop]}
(1-indexed, half-open).}
\item{\code{segment_coefs}}{Matrix \verb{(num_signals x p)}.}
\item{\code{segment_intercepts}}{Numeric vector or \code{NULL}.}
}
}
\description{
Selects the number of changepoints from \verb{\{0, …, max_num_chgpts\}} by
interleaved cross-validation, then refits on the full data.
}
\examples{
# Limit BLAS/OpenMP threads so example CPU time stays proportional to
# elapsed time on multicore CRAN machines.
Sys.setenv(
  OMP_NUM_THREADS = "1",
  OPENBLAS_NUM_THREADS = "1",
  MKL_NUM_THREADS = "1",
  BLAS_NUM_THREADS = "1"
)

if (nzchar(Sys.getenv("RETICULATE_PYTHON")) &&
    weightederm_examples_available("WERMLeastSquaresCV")) {
  set.seed(10)
  n <- 30L; p <- 2L
  X <- matrix(rnorm(n * p), n, p)
  y <- c(
    X[1:10, ] \%*\% c(3.5, 0),
    X[11:20, ] \%*\% c(-3.5, 0),
    X[21:30, ] \%*\% c(3.5, 0)
  ) + rnorm(n, sd = 0.05)
  fit <- werm_least_squares_cv(X, y, max_num_chgpts = 2L, cv = 3L,
                               delta = 3L, fit_intercept = FALSE)
  fit$best_num_chgpts
  fit$changepoints
  fit$cv_results
}

}
