sklears-feature-selection 0.1.2

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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//! Regularization-based feature selection methods

use crate::base::SelectorMixin;
use scirs2_core::ndarray::{Array1, Array2};
// For now, let's use a simple approach without external linalg
// We'll implement a basic solve using Gaussian elimination or use the pseudoinverse
use sklears_core::{
    error::{validate, Result as SklResult, SklearsError},
    traits::{Estimator, Fit, Trained, Transform, Untrained},
    types::Float,
};
use std::marker::PhantomData;

/// LASSO-based feature selection
/// Uses L1 regularization to automatically select features by setting coefficients to zero
#[derive(Debug, Clone)]
pub struct LassoSelector<State = Untrained> {
    alpha: f64,
    max_iter: usize,
    tolerance: f64,
    threshold: Option<f64>,
    state: PhantomData<State>,
    // Trained state
    coefficients_: Option<Array1<Float>>,
    selected_features_: Option<Vec<usize>>,
    n_features_: Option<usize>,
}

impl LassoSelector<Untrained> {
    /// Create a new LASSO selector
    pub fn new() -> Self {
        Self {
            alpha: 1.0,
            max_iter: 1000,
            tolerance: 1e-4,
            threshold: None,
            state: PhantomData,
            coefficients_: None,
            selected_features_: None,
            n_features_: None,
        }
    }

    /// Set the regularization parameter alpha
    pub fn alpha(mut self, alpha: f64) -> Result<Self, SklearsError> {
        if alpha < 0.0 {
            return Err(SklearsError::InvalidInput(
                "alpha must be non-negative".to_string(),
            ));
        }
        self.alpha = alpha;
        Ok(self)
    }

    /// Set maximum number of iterations
    pub fn max_iter(mut self, max_iter: usize) -> Self {
        self.max_iter = max_iter;
        self
    }

    /// Set convergence tolerance
    pub fn tolerance(mut self, tolerance: f64) -> Self {
        self.tolerance = tolerance;
        self
    }

    /// Set threshold for feature selection (if None, uses mean of absolute coefficients)
    pub fn threshold(mut self, threshold: Option<f64>) -> Self {
        self.threshold = threshold;
        self
    }
}

impl Default for LassoSelector<Untrained> {
    fn default() -> Self {
        Self::new()
    }
}

impl Estimator for LassoSelector<Untrained> {
    type Config = ();
    type Error = SklearsError;
    type Float = f64;

    fn config(&self) -> &Self::Config {
        &()
    }
}

impl Fit<Array2<Float>, Array1<Float>> for LassoSelector<Untrained> {
    type Fitted = LassoSelector<Trained>;

    fn fit(self, x: &Array2<Float>, y: &Array1<Float>) -> SklResult<Self::Fitted> {
        validate::check_consistent_length(x, y)?;

        let (n_samples, n_features) = x.dim();
        if n_samples < 2 {
            return Err(SklearsError::InvalidInput(
                "LASSO requires at least 2 samples".to_string(),
            ));
        }

        // Normalize features for LASSO
        let (x_normalized, _x_mean, x_std) = normalize_and_center(x)?;
        let y_mean = y.mean().unwrap_or(0.0);
        let y_centered: Array1<Float> = y - y_mean;

        // Fit LASSO using coordinate descent
        let mut coefficients = Array1::zeros(n_features);

        for _iter in 0..self.max_iter {
            let old_coefficients = coefficients.clone();

            for j in 0..n_features {
                if x_std[j] <= Float::EPSILON {
                    continue; // Skip zero-variance features
                }

                // Compute residual without feature j
                let mut residual = y_centered.clone();
                for k in 0..n_features {
                    if k != j {
                        let x_k = x_normalized.column(k);
                        for i in 0..n_samples {
                            residual[i] -= coefficients[k] * x_k[i];
                        }
                    }
                }

                // Compute correlation with residual
                let x_j = x_normalized.column(j);
                let rho = x_j.dot(&residual) / n_samples as Float;

                // Soft thresholding (LASSO update)
                coefficients[j] = soft_threshold(rho, self.alpha);
            }

            // Check convergence
            let diff = (&coefficients - &old_coefficients).mapv(|x| x.abs()).sum();
            if diff < self.tolerance {
                break;
            }
        }

        // Rescale coefficients back to original scale
        for j in 0..n_features {
            if x_std[j] > Float::EPSILON {
                coefficients[j] /= x_std[j];
            }
        }

        // Select features based on threshold
        let threshold = self.threshold.unwrap_or_else(|| {
            let abs_coeffs: Array1<Float> = coefficients.mapv(|x| x.abs());
            abs_coeffs.mean().unwrap_or(0.0)
        });

        let selected_features: Vec<usize> = coefficients
            .iter()
            .enumerate()
            .filter(|(_, &coeff)| coeff.abs() > threshold)
            .map(|(idx, _)| idx)
            .collect();

        if selected_features.is_empty() {
            return Err(SklearsError::InvalidInput(
                "No features selected by LASSO. Try reducing alpha or threshold.".to_string(),
            ));
        }

        Ok(LassoSelector {
            alpha: self.alpha,
            max_iter: self.max_iter,
            tolerance: self.tolerance,
            threshold: self.threshold,
            state: PhantomData,
            coefficients_: Some(coefficients),
            selected_features_: Some(selected_features),
            n_features_: Some(n_features),
        })
    }
}

impl Transform<Array2<Float>> for LassoSelector<Trained> {
    fn transform(&self, x: &Array2<Float>) -> SklResult<Array2<Float>> {
        validate::check_n_features(x, self.n_features_.expect("operation should succeed"))?;

        let selected_features = self
            .selected_features_
            .as_ref()
            .expect("operation should succeed");
        let n_samples = x.nrows();
        let k = selected_features.len();
        let mut x_new = Array2::zeros((n_samples, k));

        for (new_idx, &old_idx) in selected_features.iter().enumerate() {
            x_new.column_mut(new_idx).assign(&x.column(old_idx));
        }

        Ok(x_new)
    }
}

impl SelectorMixin for LassoSelector<Trained> {
    fn get_support(&self) -> SklResult<Array1<bool>> {
        let n_features = self.n_features_.expect("operation should succeed");
        let selected_features = self
            .selected_features_
            .as_ref()
            .expect("operation should succeed");
        let mut support = Array1::from_elem(n_features, false);

        for &idx in selected_features {
            support[idx] = true;
        }

        Ok(support)
    }

    fn transform_features(&self, indices: &[usize]) -> SklResult<Vec<usize>> {
        let selected_features = self
            .selected_features_
            .as_ref()
            .expect("operation should succeed");
        Ok(indices
            .iter()
            .filter_map(|&idx| selected_features.iter().position(|&f| f == idx))
            .collect())
    }
}

impl LassoSelector<Trained> {
    /// Get LASSO coefficients
    pub fn coefficients(&self) -> &Array1<Float> {
        self.coefficients_
            .as_ref()
            .expect("operation should succeed")
    }

    /// Get selected features
    pub fn selected_features(&self) -> &[usize] {
        self.selected_features_
            .as_ref()
            .expect("operation should succeed")
    }
}

/// Elastic Net feature selection
/// Combines L1 (LASSO) and L2 (Ridge) regularization
#[derive(Debug, Clone)]
pub struct ElasticNetSelector<State = Untrained> {
    alpha: f64,
    l1_ratio: f64,
    max_iter: usize,
    tolerance: f64,
    threshold: Option<f64>,
    state: PhantomData<State>,
    // Trained state
    coefficients_: Option<Array1<Float>>,
    selected_features_: Option<Vec<usize>>,
    n_features_: Option<usize>,
}

impl ElasticNetSelector<Untrained> {
    /// Create a new Elastic Net selector
    pub fn new() -> Self {
        Self {
            alpha: 1.0,
            l1_ratio: 0.5,
            max_iter: 1000,
            tolerance: 1e-4,
            threshold: None,
            state: PhantomData,
            coefficients_: None,
            selected_features_: None,
            n_features_: None,
        }
    }

    /// Set the regularization parameter alpha
    pub fn alpha(mut self, alpha: f64) -> Result<Self, SklearsError> {
        if alpha < 0.0 {
            return Err(SklearsError::InvalidInput(
                "alpha must be non-negative".to_string(),
            ));
        }
        self.alpha = alpha;
        Ok(self)
    }

    /// Set the L1 ratio (0 = Ridge, 1 = LASSO)
    pub fn l1_ratio(mut self, l1_ratio: f64) -> Result<Self, SklearsError> {
        if !(0.0..=1.0).contains(&l1_ratio) {
            return Err(SklearsError::InvalidInput(
                "l1_ratio must be between 0 and 1".to_string(),
            ));
        }
        self.l1_ratio = l1_ratio;
        Ok(self)
    }

    /// Set maximum number of iterations
    pub fn max_iter(mut self, max_iter: usize) -> Self {
        self.max_iter = max_iter;
        self
    }

    /// Set convergence tolerance
    pub fn tolerance(mut self, tolerance: f64) -> Self {
        self.tolerance = tolerance;
        self
    }

    /// Set threshold for feature selection
    pub fn threshold(mut self, threshold: Option<f64>) -> Self {
        self.threshold = threshold;
        self
    }
}

impl Default for ElasticNetSelector<Untrained> {
    fn default() -> Self {
        Self::new()
    }
}

impl Estimator for ElasticNetSelector<Untrained> {
    type Config = ();
    type Error = SklearsError;
    type Float = f64;

    fn config(&self) -> &Self::Config {
        &()
    }
}

impl Fit<Array2<Float>, Array1<Float>> for ElasticNetSelector<Untrained> {
    type Fitted = ElasticNetSelector<Trained>;

    fn fit(self, x: &Array2<Float>, y: &Array1<Float>) -> SklResult<Self::Fitted> {
        validate::check_consistent_length(x, y)?;

        let (n_samples, n_features) = x.dim();
        if n_samples < 2 {
            return Err(SklearsError::InvalidInput(
                "Elastic Net requires at least 2 samples".to_string(),
            ));
        }

        // Normalize features
        let (x_normalized, _x_mean, x_std) = normalize_and_center(x)?;
        let y_mean = y.mean().unwrap_or(0.0);
        let y_centered: Array1<Float> = y - y_mean;

        // Fit Elastic Net using coordinate descent
        let mut coefficients = Array1::zeros(n_features);
        let alpha_l1 = self.alpha * self.l1_ratio;
        let alpha_l2 = self.alpha * (1.0 - self.l1_ratio);

        for _iter in 0..self.max_iter {
            let old_coefficients = coefficients.clone();

            for j in 0..n_features {
                if x_std[j] <= Float::EPSILON {
                    continue;
                }

                // Compute residual without feature j
                let mut residual = y_centered.clone();
                for k in 0..n_features {
                    if k != j {
                        let x_k = x_normalized.column(k);
                        for i in 0..n_samples {
                            residual[i] -= coefficients[k] * x_k[i];
                        }
                    }
                }

                // Compute correlation with residual
                let x_j = x_normalized.column(j);
                let rho = x_j.dot(&residual) / n_samples as Float;

                // Elastic Net update (soft thresholding with L2 penalty)
                let denominator = 1.0 + alpha_l2;
                coefficients[j] = soft_threshold(rho, alpha_l1) / denominator;
            }

            // Check convergence
            let diff = (&coefficients - &old_coefficients).mapv(|x| x.abs()).sum();
            if diff < self.tolerance {
                break;
            }
        }

        // Rescale coefficients back to original scale
        for j in 0..n_features {
            if x_std[j] > Float::EPSILON {
                coefficients[j] /= x_std[j];
            }
        }

        // Select features based on threshold
        let threshold = self.threshold.unwrap_or_else(|| {
            let abs_coeffs: Array1<Float> = coefficients.mapv(|x| x.abs());
            abs_coeffs.mean().unwrap_or(0.0)
        });

        let selected_features: Vec<usize> = coefficients
            .iter()
            .enumerate()
            .filter(|(_, &coeff)| coeff.abs() > threshold)
            .map(|(idx, _)| idx)
            .collect();

        if selected_features.is_empty() {
            return Err(SklearsError::InvalidInput(
                "No features selected by Elastic Net. Try reducing alpha or threshold.".to_string(),
            ));
        }

        Ok(ElasticNetSelector {
            alpha: self.alpha,
            l1_ratio: self.l1_ratio,
            max_iter: self.max_iter,
            tolerance: self.tolerance,
            threshold: self.threshold,
            state: PhantomData,
            coefficients_: Some(coefficients),
            selected_features_: Some(selected_features),
            n_features_: Some(n_features),
        })
    }
}

impl Transform<Array2<Float>> for ElasticNetSelector<Trained> {
    fn transform(&self, x: &Array2<Float>) -> SklResult<Array2<Float>> {
        validate::check_n_features(x, self.n_features_.expect("operation should succeed"))?;

        let selected_features = self
            .selected_features_
            .as_ref()
            .expect("operation should succeed");
        let n_samples = x.nrows();
        let k = selected_features.len();
        let mut x_new = Array2::zeros((n_samples, k));

        for (new_idx, &old_idx) in selected_features.iter().enumerate() {
            x_new.column_mut(new_idx).assign(&x.column(old_idx));
        }

        Ok(x_new)
    }
}

impl SelectorMixin for ElasticNetSelector<Trained> {
    fn get_support(&self) -> SklResult<Array1<bool>> {
        let n_features = self.n_features_.expect("operation should succeed");
        let selected_features = self
            .selected_features_
            .as_ref()
            .expect("operation should succeed");
        let mut support = Array1::from_elem(n_features, false);

        for &idx in selected_features {
            support[idx] = true;
        }

        Ok(support)
    }

    fn transform_features(&self, indices: &[usize]) -> SklResult<Vec<usize>> {
        let selected_features = self
            .selected_features_
            .as_ref()
            .expect("operation should succeed");
        Ok(indices
            .iter()
            .filter_map(|&idx| selected_features.iter().position(|&f| f == idx))
            .collect())
    }
}

impl ElasticNetSelector<Trained> {
    /// Get Elastic Net coefficients
    pub fn coefficients(&self) -> &Array1<Float> {
        self.coefficients_
            .as_ref()
            .expect("operation should succeed")
    }

    /// Get selected features
    pub fn selected_features(&self) -> &[usize] {
        self.selected_features_
            .as_ref()
            .expect("operation should succeed")
    }
}

// Helper functions

/// Soft thresholding function for LASSO
fn soft_threshold(x: Float, threshold: Float) -> Float {
    if x > threshold {
        x - threshold
    } else if x < -threshold {
        x + threshold
    } else {
        0.0
    }
}

/// Normalize and center features
fn normalize_and_center(
    x: &Array2<Float>,
) -> SklResult<(Array2<Float>, Array1<Float>, Array1<Float>)> {
    let (n_samples, n_features) = x.dim();
    let mut x_normalized = Array2::zeros((n_samples, n_features));
    let mut x_mean = Array1::zeros(n_features);
    let mut x_std = Array1::zeros(n_features);

    // Compute means
    for j in 0..n_features {
        x_mean[j] = x.column(j).mean().unwrap_or(0.0);
    }

    // Center the data
    for j in 0..n_features {
        for i in 0..n_samples {
            x_normalized[[i, j]] = x[[i, j]] - x_mean[j];
        }
    }

    // Compute standard deviations
    for j in 0..n_features {
        let variance = x_normalized.column(j).mapv(|x| x * x).mean().unwrap_or(0.0);
        x_std[j] = variance.sqrt();

        // Normalize if std > 0
        if x_std[j] > Float::EPSILON {
            for i in 0..n_samples {
                x_normalized[[i, j]] /= x_std[j];
            }
        }
    }

    Ok((x_normalized, x_mean, x_std))
}

/// Ridge Regression feature selection
/// Uses Ridge regression coefficients to select features
#[derive(Debug, Clone)]
pub struct RidgeSelector<State = Untrained> {
    alpha: f64,
    threshold: Option<f64>,
    max_features: Option<usize>,
    state: PhantomData<State>,
    // Trained state
    coefficients_: Option<Array1<Float>>,
    selected_features_: Option<Vec<usize>>,
    n_features_: Option<usize>,
}

impl RidgeSelector<Untrained> {
    /// Create a new Ridge selector
    pub fn new() -> Self {
        Self {
            alpha: 1.0,
            threshold: None,
            max_features: None,
            state: PhantomData,
            coefficients_: None,
            selected_features_: None,
            n_features_: None,
        }
    }

    /// Set the regularization parameter alpha
    pub fn alpha(mut self, alpha: f64) -> Result<Self, SklearsError> {
        if alpha < 0.0 {
            return Err(SklearsError::InvalidInput(
                "alpha must be non-negative".to_string(),
            ));
        }
        self.alpha = alpha;
        Ok(self)
    }

    /// Set threshold for feature selection (if None, uses mean of absolute coefficients)
    pub fn threshold(mut self, threshold: Option<f64>) -> Self {
        self.threshold = threshold;
        self
    }

    /// Set maximum number of features to select
    pub fn max_features(mut self, max_features: Option<usize>) -> Self {
        self.max_features = max_features;
        self
    }

    /// Simple solve for linear system Ax = b using Gaussian elimination
    fn simple_solve(&self, a: &Array2<f64>, b: &Array1<f64>) -> SklResult<Array1<f64>> {
        let n = a.nrows();
        if n != a.ncols() {
            return Err(SklearsError::FitError("Matrix must be square".to_string()));
        }
        if n != b.len() {
            return Err(SklearsError::FitError("Dimension mismatch".to_string()));
        }

        // Simple approach: use iterative method (Jacobi iteration)
        // For a well-conditioned ridge system, this should converge
        let mut x = Array1::zeros(n);
        let max_iter = 1000;
        let tolerance = 1e-6;

        for _ in 0..max_iter {
            let mut x_new = Array1::zeros(n);
            for i in 0..n {
                let mut sum = 0.0;
                for j in 0..n {
                    if i != j {
                        sum += a[[i, j]] * x[j];
                    }
                }
                x_new[i] = (b[i] - sum) / a[[i, i]];
            }

            // Check convergence
            let diff: f64 = x_new
                .iter()
                .zip(x.iter())
                .map(|(a, b): (&f64, &f64)| (a - b).abs())
                .sum();
            if diff < tolerance {
                return Ok(x_new);
            }
            x = x_new;
        }

        // If we reach here, convergence failed - return best attempt
        Ok(x)
    }
}

impl Default for RidgeSelector<Untrained> {
    fn default() -> Self {
        Self::new()
    }
}

impl Estimator for RidgeSelector<Untrained> {
    type Config = ();
    type Error = SklearsError;
    type Float = f64;

    fn config(&self) -> &Self::Config {
        &()
    }
}

impl Fit<Array2<Float>, Array1<Float>> for RidgeSelector<Untrained> {
    type Fitted = RidgeSelector<Trained>;

    fn fit(self, x: &Array2<Float>, y: &Array1<Float>) -> SklResult<Self::Fitted> {
        validate::check_consistent_length(x, y)?;

        let (n_samples, n_features) = x.dim();
        if n_samples < 2 {
            return Err(SklearsError::InvalidInput(
                "Ridge requires at least 2 samples".to_string(),
            ));
        }

        // Solve Ridge regression: (X^T X + alpha * I) beta = X^T y
        let xtx = x.t().dot(x);
        let xty = x.t().dot(y);

        // Add ridge penalty to diagonal
        let mut xtx_ridge = xtx;
        for i in 0..n_features {
            xtx_ridge[[i, i]] += self.alpha;
        }

        // Solve for coefficients using simple approach
        // For now, use a simple pseudoinverse approach or iterative method
        let coefficients = self.simple_solve(&xtx_ridge, &xty)?;

        // Select features based on threshold
        let threshold = self.threshold.unwrap_or_else(|| {
            let abs_coeffs: Array1<Float> = coefficients.mapv(|x| x.abs());
            abs_coeffs.mean().unwrap_or(0.0)
        });

        let mut selected_features: Vec<usize> = coefficients
            .iter()
            .enumerate()
            .filter(|(_, &coeff)| coeff.abs() > threshold)
            .map(|(idx, _)| idx)
            .collect();

        // Apply max_features limit if specified
        if let Some(max_feat) = self.max_features {
            if selected_features.len() > max_feat {
                // Sort by absolute coefficient value and take top max_feat
                selected_features.sort_by(|&a, &b| {
                    coefficients[b]
                        .abs()
                        .partial_cmp(&coefficients[a].abs())
                        .expect("operation should succeed")
                });
                selected_features.truncate(max_feat);
                selected_features.sort(); // Restore original order
            }
        }

        if selected_features.is_empty() {
            return Err(SklearsError::InvalidInput(
                "No features selected by Ridge. Try reducing alpha or threshold.".to_string(),
            ));
        }

        Ok(RidgeSelector {
            alpha: self.alpha,
            threshold: self.threshold,
            max_features: self.max_features,
            state: PhantomData,
            coefficients_: Some(coefficients),
            selected_features_: Some(selected_features),
            n_features_: Some(n_features),
        })
    }
}

impl Transform<Array2<Float>> for RidgeSelector<Trained> {
    fn transform(&self, x: &Array2<Float>) -> SklResult<Array2<Float>> {
        validate::check_n_features(x, self.n_features_.expect("operation should succeed"))?;

        let selected_features = self
            .selected_features_
            .as_ref()
            .expect("operation should succeed");
        let n_samples = x.nrows();
        let k = selected_features.len();
        let mut x_new = Array2::zeros((n_samples, k));

        for (new_idx, &old_idx) in selected_features.iter().enumerate() {
            x_new.column_mut(new_idx).assign(&x.column(old_idx));
        }

        Ok(x_new)
    }
}

impl SelectorMixin for RidgeSelector<Trained> {
    fn get_support(&self) -> SklResult<Array1<bool>> {
        let n_features = self.n_features_.expect("operation should succeed");
        let selected_features = self
            .selected_features_
            .as_ref()
            .expect("operation should succeed");
        let mut support = Array1::from_elem(n_features, false);

        for &idx in selected_features {
            support[idx] = true;
        }

        Ok(support)
    }

    fn transform_features(&self, indices: &[usize]) -> SklResult<Vec<usize>> {
        let selected_features = self
            .selected_features_
            .as_ref()
            .expect("operation should succeed");
        Ok(indices
            .iter()
            .filter_map(|&idx| selected_features.iter().position(|&f| f == idx))
            .collect())
    }
}

impl RidgeSelector<Trained> {
    /// Get Ridge coefficients
    pub fn coefficients(&self) -> &Array1<Float> {
        self.coefficients_
            .as_ref()
            .expect("operation should succeed")
    }

    /// Get selected features
    pub fn selected_features(&self) -> &[usize] {
        self.selected_features_
            .as_ref()
            .expect("operation should succeed")
    }
}