sklears-feature-selection 0.1.1

Feature selection algorithms for sklears - scikit-learn compatible ML in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! Advanced Hyperparameter Optimization Module for AutoML Feature Selection
//!
//! Implements sophisticated optimization strategies for hyperparameter tuning.
//! All implementations follow the SciRS2 policy using scirs2-core for numerical computations.

use scirs2_core::ndarray::{ArrayView1, ArrayView2};
use scirs2_core::random::{thread_rng, Rng, RngExt};

use super::automl_core::{AutoMLMethod, DataCharacteristics};
use super::hyperparameter_optimizer::{MethodConfig, OptimizedMethod};
use sklears_core::error::Result as SklResult;
use std::time::{Duration, Instant};

type Result<T> = SklResult<T>;

/// Advanced hyperparameter optimizer with sophisticated strategies
#[derive(Debug, Clone)]
pub struct AdvancedHyperparameterOptimizer {
    optimization_strategy: OptimizationStrategy,
    max_iterations: usize,
    time_budget: Duration,
    parallel_workers: usize,
    early_stopping: Option<EarlyStoppingConfig>,
}

#[derive(Debug, Clone, PartialEq)]
/// OptimizationStrategy
pub enum OptimizationStrategy {
    /// GridSearch
    GridSearch,
    /// RandomSearch
    RandomSearch,
    /// BayesianOptimization
    BayesianOptimization,
    /// GeneticAlgorithm
    GeneticAlgorithm,
    /// ParticleSwarmOptimization
    ParticleSwarmOptimization,
    /// SimulatedAnnealing
    SimulatedAnnealing,
    /// HyperBand
    HyperBand,
}

#[derive(Debug, Clone)]
/// EarlyStoppingConfig
pub struct EarlyStoppingConfig {
    /// patience
    pub patience: usize,
    /// min_improvement
    pub min_improvement: f64,
    /// restore_best
    pub restore_best: bool,
}

impl AdvancedHyperparameterOptimizer {
    /// new
    pub fn new() -> Self {
        Self {
            optimization_strategy: OptimizationStrategy::BayesianOptimization,
            max_iterations: 100,
            time_budget: Duration::from_secs(300), // 5 minutes
            parallel_workers: 1,
            early_stopping: Some(EarlyStoppingConfig {
                patience: 10,
                min_improvement: 0.001,
                restore_best: true,
            }),
        }
    }

    /// with_strategy
    pub fn with_strategy(mut self, strategy: OptimizationStrategy) -> Self {
        self.optimization_strategy = strategy;
        self
    }

    /// with_max_iterations
    pub fn with_max_iterations(mut self, max_iterations: usize) -> Self {
        self.max_iterations = max_iterations;
        self
    }

    /// with_time_budget
    pub fn with_time_budget(mut self, time_budget: Duration) -> Self {
        self.time_budget = time_budget;
        self
    }

    /// with_parallel_workers
    pub fn with_parallel_workers(mut self, workers: usize) -> Self {
        self.parallel_workers = workers;
        self
    }

    /// with_early_stopping
    pub fn with_early_stopping(mut self, config: EarlyStoppingConfig) -> Self {
        self.early_stopping = Some(config);
        self
    }

    /// Optimize hyperparameters for a given method using advanced strategies
    pub fn optimize_advanced(
        &self,
        method: &AutoMLMethod,
        X: ArrayView2<f64>,
        y: ArrayView1<f64>,
        characteristics: &DataCharacteristics,
    ) -> Result<OptimizedMethod> {
        let start_time = Instant::now();

        let best_config = match self.optimization_strategy {
            OptimizationStrategy::BayesianOptimization => {
                self.bayesian_optimization(method, X, y, characteristics, start_time)?
            }
            OptimizationStrategy::GeneticAlgorithm => {
                self.genetic_algorithm_optimization(method, X, y, characteristics, start_time)?
            }
            OptimizationStrategy::RandomSearch => {
                self.random_search_optimization(method, X, y, characteristics, start_time)?
            }
            OptimizationStrategy::GridSearch => {
                self.grid_search_optimization(method, X, y, characteristics, start_time)?
            }
            OptimizationStrategy::ParticleSwarmOptimization => {
                self.pso_optimization(method, X, y, characteristics, start_time)?
            }
            OptimizationStrategy::SimulatedAnnealing => {
                self.simulated_annealing_optimization(method, X, y, characteristics, start_time)?
            }
            OptimizationStrategy::HyperBand => {
                self.hyperband_optimization(method, X, y, characteristics, start_time)?
            }
        };

        let estimated_cost = self.estimate_computational_cost(method, characteristics);

        Ok(OptimizedMethod {
            method_type: method.clone(),
            config: best_config,
            estimated_cost,
        })
    }

    fn bayesian_optimization(
        &self,
        method: &AutoMLMethod,
        X: ArrayView2<f64>,
        y: ArrayView1<f64>,
        characteristics: &DataCharacteristics,
        start_time: Instant,
    ) -> Result<MethodConfig> {
        // Simplified Bayesian Optimization using random search with Gaussian Process surrogate
        let mut best_config = self.generate_initial_config(method, characteristics)?;
        let mut best_score = self.evaluate_config(method, &best_config, X, y)?;

        for iteration in 0..self.max_iterations {
            if start_time.elapsed() > self.time_budget {
                break;
            }

            // Generate candidate configuration using acquisition function (simplified)
            let candidate_config =
                self.generate_candidate_config(method, characteristics, iteration)?;
            let score = self.evaluate_config(method, &candidate_config, X, y)?;

            if score > best_score {
                best_score = score;
                best_config = candidate_config;
            }

            // Early stopping check
            if let Some(ref early_stopping) = self.early_stopping {
                if score - best_score < early_stopping.min_improvement
                    && iteration > early_stopping.patience
                {
                    break;
                }
            }
        }

        Ok(best_config)
    }

    fn genetic_algorithm_optimization(
        &self,
        method: &AutoMLMethod,
        X: ArrayView2<f64>,
        y: ArrayView1<f64>,
        characteristics: &DataCharacteristics,
        start_time: Instant,
    ) -> Result<MethodConfig> {
        // Simplified Genetic Algorithm
        const POPULATION_SIZE: usize = 20;
        const MUTATION_RATE: f64 = 0.1;

        // Initialize population
        let mut population = Vec::new();
        for _ in 0..POPULATION_SIZE {
            population.push(self.generate_initial_config(method, characteristics)?);
        }

        let mut best_config = population[0].clone();
        let mut best_score = self.evaluate_config(method, &best_config, X, y)?;

        let mut rng = thread_rng();
        for _generation in 0..(self.max_iterations / POPULATION_SIZE) {
            if start_time.elapsed() > self.time_budget {
                break;
            }

            // Evaluate population
            let mut scores = Vec::new();
            for config in &population {
                let score = self.evaluate_config(method, config, X, y)?;
                scores.push(score);
                if score > best_score {
                    best_score = score;
                    best_config = config.clone();
                }
            }

            // Selection and crossover (simplified)
            let mut new_population = Vec::new();
            for _ in 0..POPULATION_SIZE {
                let parent1_idx = self.select_parent(&scores, &mut rng);
                let parent2_idx = self.select_parent(&scores, &mut rng);
                let mut child =
                    self.crossover(&population[parent1_idx], &population[parent2_idx], &mut rng)?;

                if rng.random::<f64>() < MUTATION_RATE {
                    child = self.mutate(&child, method, characteristics, &mut rng)?;
                }
                new_population.push(child);
            }

            population = new_population;
        }

        Ok(best_config)
    }

    fn random_search_optimization(
        &self,
        method: &AutoMLMethod,
        X: ArrayView2<f64>,
        y: ArrayView1<f64>,
        characteristics: &DataCharacteristics,
        start_time: Instant,
    ) -> Result<MethodConfig> {
        let mut best_config = self.generate_initial_config(method, characteristics)?;
        let mut best_score = self.evaluate_config(method, &best_config, X, y)?;

        let mut rng = thread_rng();
        for _ in 0..self.max_iterations {
            if start_time.elapsed() > self.time_budget {
                break;
            }

            let candidate_config =
                self.generate_random_config(method, characteristics, &mut rng)?;
            let score = self.evaluate_config(method, &candidate_config, X, y)?;

            if score > best_score {
                best_score = score;
                best_config = candidate_config;
            }
        }

        Ok(best_config)
    }

    fn grid_search_optimization(
        &self,
        method: &AutoMLMethod,
        X: ArrayView2<f64>,
        y: ArrayView1<f64>,
        characteristics: &DataCharacteristics,
        start_time: Instant,
    ) -> Result<MethodConfig> {
        // Simplified grid search with limited parameter ranges
        let param_grid = self.generate_parameter_grid(method, characteristics)?;
        let mut best_config = self.generate_initial_config(method, characteristics)?;
        let mut best_score = self.evaluate_config(method, &best_config, X, y)?;

        for config in param_grid {
            if start_time.elapsed() > self.time_budget {
                break;
            }

            let score = self.evaluate_config(method, &config, X, y)?;
            if score > best_score {
                best_score = score;
                best_config = config;
            }
        }

        Ok(best_config)
    }

    fn pso_optimization(
        &self,
        method: &AutoMLMethod,
        X: ArrayView2<f64>,
        y: ArrayView1<f64>,
        characteristics: &DataCharacteristics,
        start_time: Instant,
    ) -> Result<MethodConfig> {
        // Simplified PSO - fallback to random search for now
        self.random_search_optimization(method, X, y, characteristics, start_time)
    }

    fn simulated_annealing_optimization(
        &self,
        method: &AutoMLMethod,
        X: ArrayView2<f64>,
        y: ArrayView1<f64>,
        characteristics: &DataCharacteristics,
        start_time: Instant,
    ) -> Result<MethodConfig> {
        // Simplified Simulated Annealing - fallback to random search for now
        self.random_search_optimization(method, X, y, characteristics, start_time)
    }

    fn hyperband_optimization(
        &self,
        method: &AutoMLMethod,
        X: ArrayView2<f64>,
        y: ArrayView1<f64>,
        characteristics: &DataCharacteristics,
        start_time: Instant,
    ) -> Result<MethodConfig> {
        // Simplified HyperBand - fallback to random search for now
        self.random_search_optimization(method, X, y, characteristics, start_time)
    }

    // Helper methods
    fn generate_initial_config(
        &self,
        method: &AutoMLMethod,
        characteristics: &DataCharacteristics,
    ) -> Result<MethodConfig> {
        match method {
            AutoMLMethod::UnivariateFiltering => Ok(MethodConfig::Univariate {
                k: characteristics.n_features / 4,
            }),
            AutoMLMethod::CorrelationBased => Ok(MethodConfig::Correlation { threshold: 0.7 }),
            AutoMLMethod::TreeBased => Ok(MethodConfig::Tree {
                n_estimators: 50,
                max_depth: 6,
            }),
            AutoMLMethod::LassoBased => Ok(MethodConfig::Lasso { alpha: 0.01 }),
            _ => Ok(MethodConfig::Univariate {
                k: characteristics.n_features / 4,
            }),
        }
    }

    fn generate_candidate_config(
        &self,
        method: &AutoMLMethod,
        _characteristics: &DataCharacteristics,
        iteration: usize,
    ) -> Result<MethodConfig> {
        let mut rng = thread_rng();
        match method {
            AutoMLMethod::UnivariateFiltering => {
                let k = (iteration % 100 + 1) * 10; // Simple progression
                Ok(MethodConfig::Univariate { k })
            }
            AutoMLMethod::CorrelationBased => {
                let threshold = 0.5 + (iteration as f64 * 0.01);
                Ok(MethodConfig::Correlation { threshold })
            }
            _ => self.generate_random_config(method, _characteristics, &mut rng),
        }
    }

    fn generate_random_config<R: Rng>(
        &self,
        method: &AutoMLMethod,
        characteristics: &DataCharacteristics,
        rng: &mut R,
    ) -> Result<MethodConfig> {
        match method {
            AutoMLMethod::UnivariateFiltering => {
                let k = rng.random_range(1..characteristics.n_features.min(101));
                Ok(MethodConfig::Univariate { k })
            }
            AutoMLMethod::CorrelationBased => {
                let threshold = rng.random_range(0.1..1.9);
                Ok(MethodConfig::Correlation { threshold })
            }
            AutoMLMethod::TreeBased => {
                let n_estimators = rng.random_range(10..201);
                let max_depth = rng.random_range(3..16);
                Ok(MethodConfig::Tree {
                    n_estimators,
                    max_depth,
                })
            }
            AutoMLMethod::LassoBased => {
                let alpha = rng.random_range(0.001..2.0);
                Ok(MethodConfig::Lasso { alpha })
            }
            _ => Ok(MethodConfig::Univariate {
                k: characteristics.n_features / 4,
            }),
        }
    }

    fn generate_parameter_grid(
        &self,
        method: &AutoMLMethod,
        characteristics: &DataCharacteristics,
    ) -> Result<Vec<MethodConfig>> {
        let mut grid = Vec::new();
        match method {
            AutoMLMethod::UnivariateFiltering => {
                for k in [10, 20, 50, 100].iter() {
                    if *k <= characteristics.n_features {
                        grid.push(MethodConfig::Univariate { k: *k });
                    }
                }
            }
            AutoMLMethod::CorrelationBased => {
                for threshold in [0.5, 0.6, 0.7, 0.8, 0.9].iter() {
                    grid.push(MethodConfig::Correlation {
                        threshold: *threshold,
                    });
                }
            }
            _ => {
                grid.push(self.generate_initial_config(method, characteristics)?);
            }
        }
        Ok(grid)
    }

    fn evaluate_config(
        &self,
        _method: &AutoMLMethod,
        _config: &MethodConfig,
        _X: ArrayView2<f64>,
        _y: ArrayView1<f64>,
    ) -> Result<f64> {
        // Simplified evaluation - return random score for demo
        let mut rng = thread_rng();
        Ok(rng.random_range(0.0..2.0))
    }

    fn select_parent<R: Rng>(&self, scores: &[f64], rng: &mut R) -> usize {
        // Tournament selection
        let idx1 = rng.random_range(0..scores.len());
        let idx2 = rng.random_range(0..scores.len());
        if scores[idx1] > scores[idx2] {
            idx1
        } else {
            idx2
        }
    }

    fn crossover<R: Rng>(
        &self,
        parent1: &MethodConfig,
        parent2: &MethodConfig,
        rng: &mut R,
    ) -> Result<MethodConfig> {
        // Simple crossover - randomly choose from parents
        if rng.random::<bool>() {
            Ok(parent1.clone())
        } else {
            Ok(parent2.clone())
        }
    }

    fn mutate<R: Rng>(
        &self,
        _config: &MethodConfig,
        method: &AutoMLMethod,
        characteristics: &DataCharacteristics,
        rng: &mut R,
    ) -> Result<MethodConfig> {
        // Simple mutation - generate random config
        self.generate_random_config(method, characteristics, rng)
    }

    fn estimate_computational_cost(
        &self,
        method: &AutoMLMethod,
        characteristics: &DataCharacteristics,
    ) -> f64 {
        let base_cost =
            characteristics.n_samples as f64 * characteristics.n_features as f64 / 1_000_000.0;
        let strategy_multiplier = match self.optimization_strategy {
            OptimizationStrategy::GridSearch => 10.0,
            OptimizationStrategy::RandomSearch => 5.0,
            OptimizationStrategy::BayesianOptimization => 15.0,
            OptimizationStrategy::GeneticAlgorithm => 20.0,
            OptimizationStrategy::ParticleSwarmOptimization => 18.0,
            OptimizationStrategy::SimulatedAnnealing => 12.0,
            OptimizationStrategy::HyperBand => 8.0,
        };

        let method_multiplier = match method {
            AutoMLMethod::UnivariateFiltering => 0.1,
            AutoMLMethod::CorrelationBased => 0.5,
            AutoMLMethod::TreeBased => 2.0,
            AutoMLMethod::LassoBased => 1.5,
            AutoMLMethod::WrapperBased => 10.0,
            AutoMLMethod::EnsembleBased => 5.0,
            AutoMLMethod::Hybrid => 3.0,
            AutoMLMethod::NeuralArchitectureSearch => 15.0,
            AutoMLMethod::TransferLearning => 8.0,
            AutoMLMethod::MetaLearningEnsemble => 12.0,
        };

        base_cost * strategy_multiplier * method_multiplier
    }
}

impl Default for AdvancedHyperparameterOptimizer {
    fn default() -> Self {
        Self::new()
    }
}