41 std::map<std::string, double>
params;
112 {
"gamma", { 0.0 } },
121std::vector<std::map<std::string, double>>
122createGrid(
const std::map<std::string, std::vector<double>>& param_values);
125findBestParameters(
CvResult& cv_result,
const std::unique_ptr<Score>& scorer);
129fitToFold(Eigen::MatrixBase<T>& x,
130 const Eigen::MatrixXd& y,
132 const std::unique_ptr<Loss>& loss,
133 const std::unique_ptr<Score>& scorer,
134 const Eigen::ArrayXd& alphas,
138 const double gamma = 0.0,
139 const bool copy_x =
true)
141 Eigen::ArrayXd scores = Eigen::ArrayXd::Zero(alphas.size());
146 auto [x_train, y_train, x_test, y_test] = folds.
split(x, y, fold, rep);
148 auto path = thread_model.
path(x_train, y_train, alphas);
151 path = thread_model.
relax(path, x_train, y_train, gamma);
154 for (
int j = 0; j < path.size(); ++j) {
155 auto eta = path(j).
predict(x_test,
"linear");
156 scores(j) = scorer->eval(eta, y_test, loss);
166 auto x_train = x(train_idx, all);
167 auto x_test = x(test_idx, all);
169 Eigen::MatrixXd y_train = y(train_idx, all);
170 Eigen::MatrixXd y_test = y(test_idx, all);
172 auto path = thread_model.
path(x_train, y_train, alphas);
175 path = thread_model.
relax(path, x_train, y_train, gamma);
178 for (
int j = 0; j < path.size(); ++j) {
179 auto eta = path(j).
predict(x_test,
"linear");
180 scores(j) = scorer->eval(eta, y_test, loss);
189fitToFold(Eigen::SparseMatrixBase<T>& x,
190 const Eigen::MatrixXd& y,
192 const std::unique_ptr<Loss>& loss,
193 const std::unique_ptr<Score>& scorer,
194 const Eigen::ArrayXd& alphas,
198 const double gamma = 0.0,
199 const bool copy_x =
true)
201 thread_model.setModifyX(
true);
203 auto [x_train, y_train, x_test, y_test] = folds.split(x, y, fold, rep);
205 auto path = thread_model.path(x_train, y_train, alphas);
208 path = thread_model.relax(path, x_train, y_train, gamma);
211 Eigen::ArrayXd scores = Eigen::ArrayXd::Zero(path.size());
213 for (
int j = 0; j < path.size(); ++j) {
214 auto eta = path(j).predict(x_test,
"linear");
215 scores(j) = scorer->eval(eta, y_test, loss);
249 Eigen::EigenBase<T>& x,
250 const Eigen::MatrixXd& y_in,
259 auto y = loss->preprocessResponse(y_in);
262 auto hyperparams = config.default_hyperparams;
265 for (
const auto& [key, values] : config.hyperparams) {
266 hyperparams[key] = values;
269 auto grid = detail::createGrid(hyperparams);
273 config.predefined_folds.has_value()
274 ?
Folds(*config.predefined_folds)
275 :
Folds(n, config.n_folds, config.n_repeats, config.random_seed);
279 for (
const auto& params : grid) {
283 double q = params.at(
"q");
284 double gamma = params.at(
"gamma");
288 auto initial_path = model.
path(x, y);
290 result.
alphas = initial_path.getAlpha();
291 int n_alpha = result.
alphas.size();
293 assert((result.
alphas > 0).all());
295 Eigen::MatrixXd scores = Eigen::MatrixXd::Zero(n_evals, n_alpha);
298 Eigen::setNbThreads(1);
302 std::vector<std::string> thread_errors(n_evals);
303 bool had_exception =
false;
306 omp_set_max_active_levels(1);
307#pragma omp parallel for num_threads(Threads::get()) \
308 shared(scores, thread_errors, had_exception)
310 for (
int i = 0; i < n_evals; ++i) {
312 auto [rep, fold] = std::div(i, folds.
numFolds());
314 Slope thread_model = model;
316 scores.row(i) = detail::fitToFold(x.derived(),
328 }
catch (
const std::exception& e) {
329 thread_errors[i] = e.what();
331#pragma omp atomic write
333 had_exception =
true;
335 thread_errors[i] =
"Unknown exception";
337#pragma omp atomic write
339 had_exception =
true;
344 std::string error_message =
"Exception(s) during cross-validation:\n";
345 for (
int i = 0; i < n_evals; ++i) {
346 if (!thread_errors[i].empty()) {
348 "Fold " + std::to_string(i) +
": " + thread_errors[i] +
"\n";
351 throw std::runtime_error(error_message);
356 result.
score = std::move(scores);
357 cv_result.
results.push_back(result);
361 Eigen::setNbThreads(0);
364 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.