42 std::map<std::string, double>
params;
113 {
"gamma", { 0.0 } },
122std::vector<std::map<std::string, double>>
123createGrid(
const std::map<std::string, std::vector<double>>& param_values);
126findBestParameters(
CvResult& cv_result,
const std::unique_ptr<Score>& scorer);
130fitToFold(Eigen::MatrixBase<T>& x,
131 const Eigen::MatrixXd& y,
133 const std::unique_ptr<Loss>& loss,
134 const std::unique_ptr<Score>& scorer,
135 const Eigen::ArrayXd& alphas,
139 const double gamma = 0.0,
140 const bool copy_x =
true)
142 Eigen::ArrayXd scores = Eigen::ArrayXd::Zero(alphas.size());
147 auto [x_train, y_train, x_test, y_test] = folds.
split(x, y, fold, rep);
149 auto path = thread_model.
path(x_train, y_train, alphas);
152 path = thread_model.
relax(path, x_train, y_train, gamma);
155 for (
int j = 0; j < path.size(); ++j) {
156 auto eta = path(j).
predict(x_test,
"linear");
157 scores(j) = scorer->eval(eta, y_test, loss);
167 auto x_train = x(train_idx, all);
168 auto x_test = x(test_idx, all);
170 Eigen::MatrixXd y_train = y(train_idx, all);
171 Eigen::MatrixXd y_test = y(test_idx, all);
173 auto path = thread_model.
path(x_train, y_train, alphas);
176 path = thread_model.
relax(path, x_train, y_train, gamma);
179 for (
int j = 0; j < path.size(); ++j) {
180 auto eta = path(j).
predict(x_test,
"linear");
181 scores(j) = scorer->eval(eta, y_test, loss);
190fitToFold(Eigen::SparseMatrixBase<T>& x,
191 const Eigen::MatrixXd& y,
193 const std::unique_ptr<Loss>& loss,
194 const std::unique_ptr<Score>& scorer,
195 const Eigen::ArrayXd& alphas,
199 const double gamma = 0.0,
200 const bool copy_x =
true)
202 thread_model.setModifyX(
true);
204 auto [x_train, y_train, x_test, y_test] = folds.split(x, y, fold, rep);
206 auto path = thread_model.path(x_train, y_train, alphas);
209 path = thread_model.relax(path, x_train, y_train, gamma);
212 Eigen::ArrayXd scores = Eigen::ArrayXd::Zero(path.size());
214 for (
int j = 0; j < path.size(); ++j) {
215 auto eta = path(j).predict(x_test,
"linear");
216 scores(j) = scorer->eval(eta, y_test, loss);
250 Eigen::EigenBase<T>& x,
251 const Eigen::MatrixXd& y_in,
260 auto y = loss->preprocessResponse(y_in);
263 auto hyperparams = config.default_hyperparams;
266 for (
const auto& [key, values] : config.hyperparams) {
267 hyperparams[key] = values;
270 auto grid = detail::createGrid(hyperparams);
274 config.predefined_folds.has_value()
275 ?
Folds(*config.predefined_folds)
276 :
Folds(n, config.n_folds, config.n_repeats, config.random_seed);
280 for (
const auto& params : grid) {
284 double q = params.at(
"q");
285 double gamma = params.at(
"gamma");
289 auto initial_path = model.
path(x, y);
291 result.
alphas = initial_path.getAlpha();
292 int n_alpha = result.
alphas.size();
294 assert((result.
alphas > 0).all());
296 Eigen::MatrixXd scores = Eigen::MatrixXd::Zero(n_evals, n_alpha);
299 Eigen::setNbThreads(1);
303 std::vector<std::string> thread_errors(n_evals);
304 std::atomic<bool> had_exception{
false };
310 omp_set_max_active_levels(1);
314#pragma omp parallel for num_threads(Threads::get()) \
315 shared(scores, thread_errors, had_exception)
317 for (
int i = 0; i < n_evals; ++i) {
319 auto [rep, fold] = std::div(i, folds.
numFolds());
321 Slope thread_model = model;
323 scores.row(i) = detail::fitToFold(x.derived(),
335 }
catch (
const std::exception& e) {
336 thread_errors[i] = e.what();
337 had_exception =
true;
339 thread_errors[i] =
"Unknown exception";
340 had_exception =
true;
345 std::string error_message =
"Exception(s) during cross-validation:\n";
346 for (
int i = 0; i < n_evals; ++i) {
347 if (!thread_errors[i].empty()) {
349 "Fold " + std::to_string(i) +
": " + thread_errors[i] +
"\n";
352 throw std::runtime_error(error_message);
357 result.
score = std::move(scores);
358 cv_result.
results.push_back(result);
362 Eigen::setNbThreads(0);
365 detail::findBestParameters(cv_result, scorer);
Manages data partitioning for cross-validation.
size_t numEvals() const
Get the total number of folds (repetitions * folds)
size_t numFolds() const
Get the number of folds.
std::vector< int > getTrainingIndices(size_t fold_idx, size_t rep_idx=0) const
Get training indices for a specific fold and repetition.
const std::vector< int > & getTestIndices(size_t fold_idx, size_t rep_idx=0) const
Get test indices for a specific fold and repetition.
auto split(Eigen::EigenBase< T > &x, const Eigen::MatrixXd &y, size_t fold_idx, size_t rep_idx=0) const
Split data into training and test sets for a specific fold and repetition.
static std::unique_ptr< Score > create(const std::string &metric)
Eigen::MatrixXd predict(Eigen::EigenBase< T > &x, const std::string &type="response") const
Predict the response for a given input matrix.
SlopePath path(Eigen::EigenBase< T > &x, const Eigen::MatrixXd &y_in, Eigen::ArrayXd alpha=Eigen::ArrayXd::Zero(0), Eigen::ArrayXd lambda=Eigen::ArrayXd::Zero(0), std::function< bool()> check_interrupt=defaultInterruptChecker)
Computes SLOPE regression solution path for multiple alpha and lambda values.
const std::string & getLossType()
Get currently defined loss type.
SlopeFit relax(const SlopeFit &fit, T &x, const Eigen::VectorXd &y_in, const double gamma=0.0, Eigen::VectorXd beta0=Eigen::VectorXd(0), Eigen::VectorXd beta=Eigen::VectorXd(0))
Relaxes a fitted SLOPE model.
void setModifyX(const bool modify_x)
Controls if x should be modified-in-place.
void setQ(double q)
Sets the q value.
Eigen compatibility layer for version differences.
Cross-validation fold management for SLOPE models.
Namespace containing SLOPE regression implementation.
std::unique_ptr< Loss > setupLoss(const std::string &loss)
Factory function to create the appropriate loss function based on the distribution family.
CvResult crossValidate(Slope model, Eigen::EigenBase< T > &x, const Eigen::MatrixXd &y_in, const CvConfig &config=CvConfig())
Performs cross-validation on a SLOPE model to select optimal hyperparameters.
Eigen::VectorXd stdDevs(const Eigen::SparseMatrixBase< T > &x)
Computes the standard deviation for each column of a matrix.
Scoring metrics for model evaluation.
SLOPE (Sorted L-One Penalized Estimation) optimization.
Configuration settings for cross-validation.
int n_repeats
Number of times to repeat the cross-validation (default: 1)
bool copy_x
Whether to copy the design matrix for each fold (default: true)
std::map< std::string, std::vector< double > > hyperparams
Map of hyperparameter names to vectors of values to evaluate.
std::optional< std::vector< std::vector< std::vector< int > > > > predefined_folds
Optional user-defined fold assignments for custom cross-validation splits.
int n_folds
Number of folds for cross-validation (default: 10)
std::string metric
Evaluation metric used for model assessment (default: "mse")
std::map< std::string, std::vector< double > > default_hyperparams
Map of hyperparameter names to vectors of values to evaluate.
uint64_t random_seed
Seed for random number generator to ensure reproducibility (default: 42)
Contains overall results from a cross-validation process.
double best_score
The score achieved by the optimal hyperparameter configuration.
std::map< std::string, double > best_params
std::vector< GridResult > results
int best_ind
Index of the best performing configuration in the results vector.
Stores cross-validation results for a specific set of hyperparameters.
Eigen::ArrayXd mean_scores
Array of scores averaged across all folds for each alpha value.
std::map< std::string, double > params
Map of hyperparameter names to their values for the configuration.
Eigen::ArrayXd std_errors
Eigen::ArrayXd alphas
Array of regularization parameters used in the regularization path.