rusty_math 0.7.0

This is a Rust library for mathematical, statistical and machine learning operations.
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
//! # Regression
//! The `linear` module structs for fitting linear models.   
//! You can fit a linear regression or polynomial model in Rust to the training data and use the model to predict the target values for test data.
//! You can also fit a ridge or lasso regression model to the training data and use the model to predict the target values for test data.
//! Logistic regression is also supported. You can fit a logistic regression model to the training data and use the model to predict the target values and their probabilities for test data.
//! # Examples
//! ```
//! use rusty_math::linear::LinearRegression;
//! let model = LinearRegression::new();
//! ```

use std::collections::HashMap;

use crate::metrics::{r2_score,accuracy};

/// # Linear Regression
/// Fits a linear regression model to the training data. The model is of the form y = b + a<sub>1</sub>x<sub>1</sub> + a<sub>2</sub>x<sub>2</sub> + ... + a<sub>n</sub>x<sub>n</sub>.  
/// The model is fit using gradient descent. The model can be used to predict the target values for test data.
/// Fields
/// - `weights`: `Vec<f64>` -  The weights of the model
/// - `intercept`: `f64` -  The intercept of the model
pub struct LinearRegression {
    pub weights: Vec<f64>,
    pub intercept: f64,
}

impl LinearRegression {
    /// Create a new LinearRegression object
    /// # Returns
    /// - `LinearRegression` -  A new LinearRegression object
    /// # Examples
    /// ```
    /// use rusty_math::linear::LinearRegression;
    /// let model = LinearRegression::new();
    /// ```
    pub fn new() -> LinearRegression {
        LinearRegression {
            weights: Vec::new(),
            intercept: 0.0,
        }
    }

    /// Fit the Linear Regression model
    /// # Parameters
    /// - `x_train`: `&Vec<Vec<f64>>` -  A reference to a vector of vectors containing the training data  
    /// - `y_train`: `&Vec<f64>` -  A reference to a vector containing the target values  
    /// - `lr`: `f64` -  The learning rate  
    /// - `n_iter`: `i32` -  The number of iterations  
    /// # Examples
    /// ```
    /// use rusty_math::linear::LinearRegression;
    /// let mut model = LinearRegression::new();
    /// let x_train = vec![vec![1.0, 2.0], vec![2.0, 3.0], vec![3.0, 4.0]];
    /// let y_train = vec![3.0, 4.0, 5.0];
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// ```
    /// # Panics
    /// If the number of samples in the training data does not match the number of samples in the target values
    pub fn fit(&mut self, x_train: &Vec<Vec<f64>>, y_train: &Vec<f64>, lr: f64, n_iter: i32) {
        let n_samples = x_train.len();
        let n_features = x_train[0].len();
        self.weights = vec![1.0; n_features];
        if n_samples != y_train.len() {
            panic!("Number of samples in training data does not match the number of samples in target values");
        }

        for _ in 0..n_iter {
            let mut y_pred = vec![0.0; n_samples];
            for i in 0..n_samples {
                for j in 0..n_features {
                    y_pred[i] += self.weights[j] * x_train[i][j];
                }
                y_pred[i] += self.intercept;
            }
            let mut dw = vec![0.0; n_features];
            let mut di = 0.0;

            for i in 0..n_samples {
                for j in 0..n_features {
                    dw[j] += (y_pred[i] - y_train[i]) * x_train[i][j];
                }
                di += y_pred[i] - y_train[i];
            }

            self.intercept -= lr * di / n_samples as f64;

            for i in 0..n_features {
                self.weights[i] -= lr * dw[i] / n_samples as f64;
            }
        }
    }

    /// Predict the target values
    /// # Parameters
    /// - `x_test`:`&Vec<Vec<f64>` -  A reference to a vector of vectors containing the test data  
    /// # Returns
    /// - `Vec<f64>` -  A vector containing the predicted target values
    /// # Examples
    /// ```
    /// use rusty_math::linear::LinearRegression;
    /// let mut model = LinearRegression::new();
    /// let x_train = vec![vec![1.0, 2.0], vec![2.0, 3.0], vec![3.0, 4.0]];
    /// let y_train = vec![3.0, 4.0, 5.0];
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let x_test = vec![vec![4.0, 5.0], vec![5.0, 6.0]];
    /// let y_pred = model.predict(&x_test);
    /// ```
    /// # Panics
    /// If the number of features in the test data does not match the number of features in the training data
    pub fn predict(&self, x_test: &Vec<Vec<f64>>) -> Vec<f64> {
        let n_samples = x_test.len();
        let n_features = x_test[0].len();
        if n_features != self.weights.len() {
            panic!("Number of features in test data does not match the number of features in training data");
        }
        let mut y_pred = vec![0.0; n_samples];

        for i in 0..n_samples {
            for j in 0..n_features {
                y_pred[i] += self.weights[j] * x_test[i][j];
            }
            y_pred[i] += self.intercept;
        }
        y_pred
    }

    /// Get the weights of the model
    /// # Returns
    /// - `Vec<f64>` -  A vector containing the weights of the model
    /// # Examples
    /// ```
    /// use rusty_math::linear::LinearRegression;
    /// let mut model = LinearRegression::new();
    /// let x_train = vec![vec![1.0, 2.0], vec![2.0, 3.0], vec![3.0, 4.0]];
    /// let y_train = vec![3.0, 4.0, 5.0];
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let weights = model.get_weights();
    /// ```
    pub fn get_weights(&self) -> Vec<f64> {
        self.weights.clone()
    }

    /// Get the intercept of the model
    /// # Returns
    /// - `f64` -  The intercept of the model
    /// # Examples
    /// ```
    /// use rusty_math::linear::LinearRegression;
    /// let mut model = LinearRegression::new();
    /// let x_train = vec![vec![1.0, 2.0], vec![2.0, 3.0], vec![3.0, 4.0]];
    /// let y_train = vec![3.0, 4.0, 5.0];
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let intercept = model.get_intercept();
    /// ```
    pub fn get_intercept(&self) -> f64 {
        self.intercept
    }

    /// Get the R<sup>2</sup> score of the model on the test data
    /// # Parameters
    /// - x_test: `&Vec<Vec<f64>>` -  A reference to a vector of vectors containing the test data
    /// - y_test: `&Vec<f64>` -  A reference to a vector containing the target values
    /// # Returns
    /// - `f64` -  The R<sup>2</sup> score of the model on the test data
    /// # Examples
    /// ```
    /// use rusty_math::linear::LinearRegression;
    /// let mut model = LinearRegression::new();
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let score = model.score(&x_test, &y_test);
    /// ```
    pub fn score(&self, x_test: &Vec<Vec<f64>>, y_test: &Vec<f64>) -> f64 {
        let y_pred = self.predict(x_test);
        r2_score(y_test, &y_pred)
    }

    /// Get the parameters of the model. The parameters are the weights and the intercept. See the field descriptions for more information. 
    /// The weights are stored in the HashMap with the key "weight_i" where i is the index of the weight.
    /// # Returns
    /// - `HashMap<String, String>` -  A HashMap containing the parameters of the model
    pub fn get_params(&self) -> HashMap<String, String> {
        let mut params = HashMap::new();
        params.insert("intercept".to_string(), self.intercept.to_string());
        for i in 0..self.weights.len() {
            params.insert(format!("weight_{}", i), self.weights[i].to_string());
        }
        params
    }
}

/// # Polynomial Regression
/// Fits a polynomial regression model to the training data. The model is of the form y = b + a<sub>1</sub>x + a<sub>2</sub>x<sup>2</sup> + ... + a<sub>n</sub>x<sup>n</sup>.  
/// The model is fit using gradient descent. The model can be used to predict the target values for test data.   
/// The degree of the polynomial can be set by the user.
/// # Examples
/// ```
/// use rusty_math::linear::PolynomialRegression;
/// let model = PolynomialRegression::new(2); // set the degree of the polynomial to 2
/// ```
/// Fields
/// - `weights`: `Vec<f64>` -  The weights of the model
/// - `intercept`: `f64` -  The intercept of the model
/// - `degree`: `usize` -  The degree of the polynomial
pub struct PolynomialRegression {
    pub weights: Vec<f64>,
    pub intercept: f64,
    pub degree: usize,
}

impl PolynomialRegression {
    /// Create a new PolynomialRegression object
    /// # Parameters
    /// - `degree`: `usize` -  The degree of the polynomial
    /// # Returns
    /// - `PolynomialRegression` -  A new PolynomialRegression object
    pub fn new(degree: usize) -> PolynomialRegression {
        PolynomialRegression {
            weights: Vec::new(),
            intercept: 0.0,
            degree: degree,
        }
    }

    /// Expand the features of the training data to include polynomial features. Called automatically by the fit and predict method.
    /// ## Warning
    /// Do not pass the expanded features to the fit method. The fit method will automatically expand the features.
    /// # Parameters
    /// - `x`: `&Vec<Vec<f64>` -  A reference to a vector of vectors containing the training data  
    /// # Returns
    /// - `Vec<Vec<f64>` -  A vector of vectors containing the expanded features  
    /// # Examples
    /// ```
    /// use rusty_math::linear::PolynomialRegression;
    /// let model = PolynomialRegression::new(2);
    /// let x_train = vec![vec![1.0, 2.0], vec![2.0, 3.0], vec![3.0, 4.0]];
    /// let x_poly = model.expand_features(&x_train);
    /// ```
    pub fn expand_features(&self, x: &Vec<Vec<f64>>) -> Vec<Vec<f64>> {
        use itertools::Itertools;
        let mut x_poly = Vec::new();
        for row in x {
            let mut row_poly = vec![1.0];
            row_poly.extend(row.clone());

            for d in 2..=self.degree {
                let mut combis = Vec::new();

                for combo in (0..row.len()).combinations_with_replacement(d) {
                    let mut product = 1.0;
                    for &i in &combo {
                        product *= row[i];
                    }
                    combis.push(product);
                }
                row_poly.extend(combis);
            }
            x_poly.push(row_poly);
        }
        x_poly
    }

    /// Fit the Polynomial Regression model. The model is fit using gradient descent.  
    /// # Parameters
    /// - `x_train`: `&Vec<Vec<f64>>` -  A reference to a vector of vectors containing the training data  
    /// - `y_train`: `&Vec<f64>` -  A reference to a vector containing the target values  
    /// - `lr`: `f64 -  The learning rate  
    /// - `n_iter`: `i32` -  The number of iterations
    /// # Examples
    /// ```
    /// use rusty_math::linear::PolynomialRegression;
    /// let mut model = PolynomialRegression::new(2);
    /// let x_train = vec![vec![1.0, 2.0], vec![2.0, 3.0], vec![3.0, 4.0]];
    /// let y_train = vec![3.0, 4.0, 5.0];
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// ```
    /// # Panics
    /// If the number of samples in the training data does not match the number of samples in the target values
    pub fn fit(&mut self, x_train: &Vec<Vec<f64>>, y_train: &Vec<f64>, lr: f64, n_iter: i32) {
        let n_samples = x_train.len();
        if n_samples != y_train.len() {
            panic!("Number of samples in training data does not match the number of samples in target values");
        }
        let x_poly = self.expand_features(x_train);
        let n_features_poly = x_poly[0].len();
        self.weights = vec![1.0; n_features_poly];
        for _ in 0..n_iter {
            let mut y_pred = vec![0.0; n_samples];
            for i in 0..n_samples {
                for j in 0..n_features_poly {
                    y_pred[i] += self.weights[j] * x_poly[i][j];
                }
            }
            let mut dw = vec![0.0; n_features_poly];
            let mut di = 0.0;
            for i in 0..n_samples {
                for j in 0..n_features_poly {
                    dw[j] += (y_pred[i] - y_train[i]) * x_poly[i][j];
                }
                di += y_pred[i] - y_train[i];
            }
            self.intercept -= lr * di / n_samples as f64;
            for i in 0..n_features_poly {
                self.weights[i] -= lr * dw[i] / n_samples as f64;
            }
        }
    }

    /// Predict the target values.
    /// # Parameters
    /// - `x_test`: `Vec<Vec<f64>` -  A reference to a vector of vectors containing the test data
    /// # Returns
    /// - `Vec<f64>` -  A vector containing the predicted target values
    /// # Examples
    /// ```
    /// use rusty_math::linear::PolynomialRegression;
    /// let mut model = PolynomialRegression::new(2);
    /// let x_train = vec![vec![1.0, 2.0], vec![2.0, 3.0], vec![3.0, 4.0]];
    /// let y_train = vec![3.0, 4.0, 5.0];
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let x_test = vec![vec![4.0, 5.0], vec![5.0, 6.0]];
    /// let y_pred = model.predict(&x_test);
    /// ```
    /// # Panics
    /// If the number of features in the test data does not match the number of features in the training data
    pub fn predict(&self, x_test: &Vec<Vec<f64>>) -> Vec<f64> {
        let n_samples = x_test.len();
        let x_poly = self.expand_features(&x_test);
        if x_poly[0].len() != self.weights.len() {
            panic!("Number of features in test data does not match the number of features in training data");
        }
        let mut y_pred = vec![0.0; n_samples];
        for i in 0..n_samples {
            for j in 0..x_poly[0].len() {
                y_pred[i] += self.weights[j] * x_poly[i][j];
            }
            y_pred[i] += self.intercept;
        }
        y_pred
    }

    /// Get the weights of the model
    /// # Returns
    /// - `Vec<f64>` -  A vector containing the weights of the model
    /// # Examples
    /// ```
    /// use rusty_math::linear::PolynomialRegression;
    /// let mut model = PolynomialRegression::new(2);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let weights = model.get_weights();
    /// ```
    pub fn get_weights(&self) -> Vec<f64> {
        self.weights.clone()
    }

    /// Get the intercept of the model
    /// # Returns
    /// - `f64` -  The intercept of the model
    /// # Examples
    /// ```
    /// use rusty_math::linear::PolynomialRegression;
    /// let mut model = PolynomialRegression::new(2);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let intercept = model.get_intercept();
    /// ```
    pub fn get_intercept(&self) -> f64 {
        self.intercept
    }

    /// Get the R<sup>2</sup> score of the model on the test data
    /// # Parameters
    /// - `x_test`: `&Vec<Vec<f64>>` -  A reference to a vector of vectors containing the test data
    /// - `y_test`: `&Vec<f64>` -  A reference to a vector containing the target values
    /// # Returns
    /// - `f64` -  The R<sup>2</sup> score of the model on the test data
    /// # Examples
    /// ```
    /// use rusty_math::linear::PolynomialRegression;
    /// let mut model = PolynomialRegression::new(2);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let score = model.score(&x_test, &y_test);
    /// ```
    pub fn score(&self, x_test: &Vec<Vec<f64>>, y_test: &Vec<f64>) -> f64 {
        let y_pred = self.predict(&x_test);
        r2_score(&y_test, &y_pred)
    }
}

/// # Ridge Regression
/// Fits a ridge regression model to the training data. The model is of the form y = b + a<sub>1</sub>x<sub>1</sub> + a<sub>2</sub>x<sub>2</sub> + ... + a<sub>n</sub>x<sub>n</sub>.
/// The model is fit using gradient descent with L2 regularization. The model can be used to predict the target values for test data.
/// # Examples
/// ```
/// use rusty_math::linear::RidgeRegression;
/// let model = RidgeRegression::new(0.01);
/// ```
/// Fields
/// - `weights`: `Vec<f64>` -  The weights of the model
/// - `intercept`: `f64` -  The intercept of the model
/// - `alpha`: `f64` -  The regularization parameter
pub struct RidgeRegression {
    pub weights: Vec<f64>,
    pub intercept: f64,
    pub alpha: f64,
}

impl RidgeRegression {
    /// Create a new RidgeRegression object
    /// # Parameters
    /// - `alpha`: `f64` -  The regularization parameter
    /// # Returns
    /// - `RidgeRegression` -  A new RidgeRegression object
    /// # Examples
    /// ```
    /// use rusty_math::linear::RidgeRegression;
    /// let model = RidgeRegression::new(0.01);
    /// ```
    pub fn new(alpha: f64) -> RidgeRegression {
        RidgeRegression {
            weights: Vec::new(),
            intercept: 0.0,
            alpha: alpha,
        }
    }

    /// Fit the Ridge Regression model. The model is fit using gradient descent with L2 regularization.
    /// # Parameters
    /// - `x_train`: `&Vec<Vec<f64>>` -  A reference to a vector of vectors containing the training data  
    /// - `y_train`: `&Vec<f64>` -  A reference to a vector containing the target values  
    /// - `lr`: `f64` -  The learning rate  
    /// - `n_iter`: `i32` -  The number of iterations  
    /// # Examples
    /// ```
    /// use rusty_math::linear::RidgeRegression;
    /// let mut model = RidgeRegression::new(0.01);
    /// let x_train = vec![vec![1.0, 2.0], vec![2.0, 3.0], vec![3.0, 4.0]];
    /// let y_train = vec![3.0, 4.0, 5.0];
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// ```
    /// # Panics
    /// If the number of samples in the training data does not match the number of samples in the target values
    pub fn fit(&mut self, x_train: &Vec<Vec<f64>>, y_train: &Vec<f64>, lr: f64, n_iter: i32) {
        let n_samples = x_train.len();
        let n_features = x_train[0].len();
        self.weights = vec![1.0; n_features];
        if n_samples != y_train.len() {
            panic!("Number of samples in training data does not match the number of samples in target values");
        }

        for _ in 0..n_iter {
            let mut y_pred = vec![0.0; n_samples];
            for i in 0..n_samples {
                for j in 0..n_features {
                    y_pred[i] += self.weights[j] * x_train[i][j];
                }
                y_pred[i] += self.intercept;
            }
            let mut dw = vec![0.0; n_features];
            let mut di = 0.0;

            for i in 0..n_samples {
                for j in 0..n_features {
                    dw[j] += (y_pred[i] - y_train[i]) * x_train[i][j];
                }
                di += y_pred[i] - y_train[i];
            }

            self.intercept -= lr * di / n_samples as f64;
            for i in 0..n_features {
                self.weights[i] -=
                    lr * (dw[i] / n_samples as f64 + self.alpha * self.weights[i].powi(2));
            }
        }
    }

    /// Predict the target values.
    /// # Parameters
    /// - `x_test`: `Vec<Vec<f64>` -  A reference to a vector of vectors containing the test data  
    /// # Returns
    /// - `Vec<f64>` -  A vector containing the predicted target values  
    /// # Examples
    /// ```
    /// use rusty_math::linear::RidgeRegression;
    /// let mut model = RidgeRegression::new(0.01);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let x_test = vec![vec![4.0, 5.0], vec![5.0, 6.0]];
    /// let y_pred = model.predict(&x_test);
    /// ```
    /// # Panics
    /// If the number of features in the test data does not match the number of features in the training data
    pub fn predict(&self, x_test: &Vec<Vec<f64>>) -> Vec<f64> {
        let n_samples = x_test.len();
        let n_features = x_test[0].len();
        if n_features != self.weights.len() {
            panic!("Number of features in test data does not match the number of features in training data");
        }
        let mut y_pred = vec![0.0; n_samples];

        for i in 0..n_samples {
            for j in 0..n_features {
                y_pred[i] += self.weights[j] * x_test[i][j];
            }
            y_pred[i] += self.intercept;
        }
        y_pred
    }

    /// Get the weights of the model
    /// # Returns
    /// - `Vec<f64>` -  A vector containing the weights of the model  
    /// # Examples
    /// ```
    /// use rusty_math::linear::RidgeRegression;
    /// let mut model = RidgeRegression::new(0.01);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let weights = model.get_weights();
    /// ```
    pub fn get_weights(&self) -> Vec<f64> {
        self.weights.clone()
    }

    /// Get the intercept of the model
    /// # Returns
    /// - `f64` -  The intercept of the model
    /// # Examples
    /// ```
    /// use rusty_math::linear::RidgeRegression;
    /// let mut model = RidgeRegression::new(0.01);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let intercept = model.get_intercept();
    /// ```
    pub fn get_intercept(&self) -> f64 {
        self.intercept
    }

    /// Get the R<sup>2</sup> score of the model on the test data
    /// # Parameters
    /// - `x_test`: `&Vec<Vec<f64>>` -  A reference to a vector of vectors containing the test data  
    /// - `y_test`: `&Vec<f64>` -  A reference to a vector containing the target values
    /// # Returns
    /// - `f64` -  The R<sup>2</sup> score of the model on the test data
    /// # Examples
    /// ```
    /// use rusty_math::linear::RidgeRegression;
    /// let mut model = RidgeRegression::new(0.01);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let score = model.score(&x_test, &y_test);
    /// ```
    pub fn score(&self, x_test: &Vec<Vec<f64>>, y_test: &Vec<f64>) -> f64 {
        let y_pred = self.predict(x_test);
        r2_score(y_test, &y_pred)
    }

    /// Get the parameters of the model. The parameters are the weights, intercept and alpha. See the field descriptions for more information.
    /// The weights are stored in the HashMap with the key "weight_i" where i is the index of the weight.
    /// # Returns
    /// - `HashMap<String, String>` -  A HashMap containing the parameters of the model
    /// # Examples
    /// ```
    /// use rusty_math::linear::RidgeRegression;
    /// let mut model = RidgeRegression::new(0.01);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let params = model.get_params();
    /// ```
    pub fn get_params(&self) -> HashMap<String, String> {
        let mut params = HashMap::new();
        params.insert("intercept".to_string(), self.intercept.to_string());
        for i in 0..self.weights.len() {
            params.insert(format!("weight_{}", i), self.weights[i].to_string());
        }
        params.insert("alpha".to_string(), self.alpha.to_string());
        params
    }
}

/// # Lasso Regression
/// Fits a lasso regression model to the training data. The model is of the form y = b + a<sub>1</sub>x<sub>1</sub> + a<sub>2</sub>x<sub>2</sub> + ... + a<sub>n</sub>x<sub>n</sub>.
/// The model is fit using gradient descent with L1 regularization. The model can be used to predict the target values for test data.
/// # Examples
/// ```
/// use rusty_math::linear::LassoRegression;
/// let model = LassoRegression::new(0.01);
/// ```
/// Fields
/// - `weights`: `Vec<f64>` -  The weights of the model
/// - `intercept`: `f64` -  The intercept of the model
/// - `alpha`: `f64` -  The regularization parameter
pub struct LassoRegression {
    pub weights: Vec<f64>,
    pub intercept: f64,
    pub alpha: f64,
}

impl LassoRegression {
    /// Create a new LassoRegression object.
    /// # Parameters
    /// - `alpha`: `f64` -  The regularization parameter
    /// # Returns
    /// - `LassoRegression` -  A new LassoRegression object
    /// # Examples
    /// ```
    /// use rusty_math::linear::LassoRegression;
    /// let model = LassoRegression::new(0.01);
    /// ```
    pub fn new(alpha: f64) -> LassoRegression {
        LassoRegression {
            weights: Vec::new(),
            intercept: 0.0,
            alpha: alpha,
        }
    }

    /// Fit the Lasso Regression model. The model is fit using gradient descent with L1 regularization.
    /// # Parameters
    /// - `x_train`: `&Vec<Vec<f64>>` -  A reference to a vector of vectors containing the training data  
    /// - `y_train`: `&Vec<f64>` -  A reference to a vector containing the target values  
    /// - `lr`: `f64` -  The learning rate  
    /// - `n_iter`: `i32` -  The number of iterations  
    /// # Examples
    /// ```
    /// use rusty_math::linear::LassoRegression;
    /// let mut model = LassoRegression::new(0.01);
    /// let x_train = vec![vec![1.0, 2.0], vec![2.0, 3.0], vec![3.0, 4.0]];
    /// let y_train = vec![3.0, 4.0, 5.0];
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// ```
    /// # Panics
    /// If the number of samples in the training data does not match the number of samples in the target values.  
    pub fn fit(&mut self, x_train: &Vec<Vec<f64>>, y_train: Vec<f64>, lr: f64, n_iters: i32) {
        let n_samples = x_train.len();
        let n_features = x_train[0].len();
        self.weights = vec![1.0; n_features];
        if n_samples != y_train.len() {
            panic!("Number of samples in training data does not match the number of samples in target values");
        }

        for _ in 0..n_iters {
            let mut y_pred = vec![0.0; n_samples];
            for i in 0..n_samples {
                for j in 0..n_features {
                    y_pred[i] += self.weights[j] * x_train[i][j];
                }
                y_pred[i] += self.intercept;
            }
            let mut dw = vec![0.0; n_features];
            let mut di = 0.0;

            for i in 0..n_samples {
                for j in 0..n_features {
                    dw[j] += (y_pred[i] - y_train[i]) * x_train[i][j];
                }
                di += y_pred[i] - y_train[i];
            }

            self.intercept -= lr * di / n_samples as f64;
            for i in 0..n_features {
                self.weights[i] -=
                    lr * (dw[i] / n_samples as f64 + self.alpha * self.weights[i].signum());
            }
        }
    }

    /// Predict the target values from the test data.  
    /// # Parameters
    /// - `x_test`: `Vec<Vec<f64>` -  A reference to a vector of vectors containing the test data
    /// # Returns
    /// - `Vec<f64>` -  A vector containing the predicted target values
    /// # Examples
    /// ```
    /// use rusty_math::linear::LassoRegression;
    /// let mut model = LassoRegression::new(0.01);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let x_test = vec![vec![4.0, 5.0], vec![5.0, 6.0]];
    /// let y_pred = model.predict(&x_test);
    /// ```
    /// # Panics
    /// If the number of features in the test data does not match the number of features in the training data
    pub fn predict(&self, x_test: &Vec<Vec<f64>>) -> Vec<f64> {
        let n_samples = x_test.len();
        let n_features = x_test[0].len();
        if n_features != self.weights.len() {
            panic!("Number of features in test data does not match the number of features in training data");
        }
        let mut y_pred = vec![0.0; n_samples];

        for i in 0..n_samples {
            for j in 0..n_features {
                y_pred[i] += self.weights[j] * x_test[i][j];
            }
            y_pred[i] += self.intercept;
        }
        y_pred
    }

    /// Get the weights of the model
    /// # Returns
    /// - `Vec<f64>` -  A vector containing the weights of the model
    /// # Examples
    /// ```
    /// use rusty_math::linear::LassoRegression;
    /// let mut model = LassoRegression::new(0.01);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let weights = model.weights();
    /// ```
    pub fn weights(&self) -> Vec<f64> {
        self.weights.clone()
    }

    /// Get the intercept of the model
    /// # Returns
    /// - `f64` -  The intercept of the model
    /// # Examples
    /// ```
    /// use rusty_math::linear::LassoRegression;
    /// let mut model = LassoRegression::new(0.01);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let intercept = model.intercept();
    /// ```
    pub fn intercept(&self) -> f64 {
        self.intercept
    }

    /// Get the R<sup>2</sup> score of the model on the test data.
    /// # Parameters
    /// - `x_test`: `&Vec<Vec<f64>>` -  A reference to a vector of vectors containing the test data  
    /// - `y_test`: `&Vec<f64>` -  A reference to a vector containing the target values      
    /// # Returns  
    /// - `f64` -  The R<sup>2</sup> score of the model on the test data
    /// # Examples
    /// ```
    /// use rusty_math::linear::LassoRegression;
    /// let mut model = LassoRegression::new(0.01);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let score = model.score(&x_test, &y_test);
    /// ```
    pub fn score(&self, x_test: &Vec<Vec<f64>>, y_test: &Vec<f64>) -> f64 {
        let y_pred = self.predict(x_test);
        r2_score(y_test, &y_pred)
    }

    /// Get the parameters of the model. The parameters are the weights, intercept and alpha. See the field descriptions for more information.
    /// The weights are stored in the HashMap with the key "weight_i" where i is the index of the weight.
    /// # Returns
    /// - `HashMap<String, String>` -  A HashMap containing the parameters of the model
    /// # Examples
    /// ```
    /// use rusty_math::linear::RidgeRegression;
    /// let mut model = RidgeRegression::new(0.01);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let params = model.get_params();
    /// ```
    pub fn get_params(&self) -> HashMap<String, String> {
        let mut params = HashMap::new();
        params.insert("intercept".to_string(), self.intercept.to_string());
        for i in 0..self.weights.len() {
            params.insert(format!("weight_{}", i), self.weights[i].to_string());
        }
        params.insert("alpha".to_string(), self.alpha.to_string());
        params
    }

}



/// # Logistic Regression
/// Fits a logistic regression model to the training data. The model is of the form y = 1 / (1 + e<sup>-(b + a<sub>1</sub>x<sub>1</sub> + a<sub>2</sub>x<sub>2</sub> + ... + a<sub>n</sub>x<sub>n</sub>)).
/// The model is fit using gradient descent of likelihood. The model can be used to predict the target values for test data.
/// # Examples
/// ```
/// use rusty_math::linear::LogisticRegression;
/// let model = LogisticRegression::new();
/// ```
/// Fields:
/// weights: `Vec<f64>` - The weights of the model
/// intercept: `f64` - The intercept of the model
pub struct LogisticRegression {
    pub weights: Vec<f64>,
    pub intercept: f64,
}

impl LogisticRegression{

    /// Create a new LogisticRegression object
    /// # Returns
    /// `LogisticRegression` - A new LogisticRegression object
    /// # Examples
    /// ```
    /// use rusty_math::linear::LogisticRegression;
    /// let model = LogisticRegression::new();
    /// ```
    pub fn new() -> LogisticRegression{
        LogisticRegression{
            weights: Vec::new(),
            intercept: 0.0,
        }
    }


    fn sigmoid(x: f64) -> f64{
        1.0 / (1.0 + (-x).exp())
    }


    /// Fit the Logistic Regression model. The model is fit using gradient descent of likelihood.
    /// # Parameters
    /// x_train: `&Vec<Vec<f64>>` - A reference to a vector of vectors containing the training data  
    /// y_train: `&Vec<f64>` - A reference to a vector containing the target values  
    /// lr: `f64` - The learning rate  
    /// n_iter: `i32` - The number of iterations  
    /// # Examples
    /// ```
    /// use rusty_math::linear::LogisticRegression;
    /// let mut model = LogisticRegression::new();
    /// let x_train = vec![vec![1.0, 2.0], vec![2.0, 3.0], vec![3.0, 4.0]];
    /// let y_train = vec![0.0, 1.0, 0.0];
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// ```
    /// # Panics
    /// If the number of samples in the training data does not match the number of samples in the target values  
    pub fn fit(&mut self, x_train: &Vec<Vec<f64>>, y_train: &Vec<f64>, lr: f64, n_iter: i32){
        let n_samples = x_train.len();
        let n_features = x_train[0].len();
        self.weights = vec![1.0; n_features];
        if n_samples != y_train.len() {
            panic!("Number of samples in training data does not match the number of samples in target values");
        }
        for _ in 0..n_iter{
            let mut y_pred = vec![0.0; n_samples];
            for i in 0..n_samples{
                for j in 0..n_features{
                    y_pred[i] += self.weights[j] * x_train[i][j];
                }
                y_pred[i] += self.intercept;
                y_pred[i] = LogisticRegression::sigmoid(y_pred[i]);
            }

            let mut dw = vec![0.0; n_features];
            let mut di = 0.0;

            for i in 0..n_samples{
                for j in 0..n_features{
                    dw[j] += (y_pred[i] - y_train[i]) * x_train[i][j];
                }
                di += y_pred[i] - y_train[i];
            }

            self.intercept -= lr * di / n_samples as f64;
            for i in 0..n_features{
                self.weights[i] -= lr * dw[i] / n_samples as f64;
            }


            
        }

    }

    /// Predict the target probabilities for the test data.
    /// # Parameters
    /// x_test: `Vec<Vec<f64>` - A reference to a vector of vectors containing the test data
    /// # Returns
    /// `Vec<Vec<f64>` - A vector of vectors containing the predicted probabilities
    /// # Examples
    /// ```
    /// use rusty_math::linear::LogisticRegression;
    /// let mut model = LogisticRegression::new();
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let x_test = vec![vec![4.0, 5.0], vec![5.0, 6.0]];
    /// let y_pred = model.predict_proba(&x_test);
    /// ```
    /// # Panics
    /// If the number of features in the test data does not match the number of features in the training data
    /// # Remarks
    /// This function returns the probabilities of the positive class. The probability of the negative class is 1 - probability of the positive class.  
    /// If you want to predict the target values, you can threshold the probabilities at 0.5.
    pub fn predict_proba(&self, x_test: &Vec<Vec<f64>>) -> Vec<Vec<f64>>{
        let n_samples = x_test.len();
        let n_features = x_test[0].len();
        if n_features != self.weights.len() {
            panic!("Number of features in test data does not match the number of features in training data");
        }
        let mut y_pred = vec![vec![0.0; 2];n_samples];

        for i in 0..n_samples {
            for j in 0..n_features {
                y_pred[i][1] += self.weights[j] * x_test[i][j];
            }
            y_pred[i][1] += self.intercept;
            y_pred[i][1] = LogisticRegression::sigmoid(y_pred[i][1]);
            y_pred[i][0] = 1.0 - y_pred[i][1];
        }
        y_pred
    }


    /// Predict the target values for the test data.
    /// # Parameters
    /// x_test: `Vec<Vec<f64>` - A reference to a vector of vectors containing the test data
    /// # Returns
    /// `Vec<i32>` - A vector containing the predicted target values
    /// # Examples
    /// ```
    /// use rusty_math::linear::LogisticRegression;
    /// let mut model = LogisticRegression::new();
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let x_test = vec![vec![4.0, 5.0], vec![5.0, 6.0]];
    /// let y_pred = model.predict(&x_test);
    /// ```
    /// # Panics
    /// If the number of features in the test data does not match the number of features in the training data
    /// # Remarks
    /// This function uses the predict_proba function to predict the target values. If the probability of the positive class is greater than 0.5, the target value is 1, otherwise it is 0.
    /// This function is equivalent to calling predict_proba and then thresholding the probabilities at 0.5.
    pub fn predict(&self, x_test: &Vec<Vec<f64>>) -> Vec<i32>{
        let probs = self.predict_proba(x_test);
        let mut y_pred = vec![0; probs.len()];
        for i in 0..probs.len(){
            if probs[i][1] > probs[i][0]{
                y_pred[i] = 1;
            }
        }
        y_pred
    }

    /// Get the weights of the model
    /// # Returns
    /// `Vec<f64>` - A vector containing the weights of the model
    pub fn get_weights(&self) -> Vec<f64>{
        self.weights.clone()
    }


    /// Get the intercept of the model
    /// # Returns
    /// `f64` - The intercept of the model
    pub fn get_intercept(&self) -> f64{
        self.intercept
    }

    /// Get the accuracy of the model on the test data
    /// # Parameters
    /// x_test: `&Vec<Vec<f64>>` - A reference to a vector of vectors containing the test data  
    /// y_test: `&Vec<f64>` - A reference to a vector containing the target values  
    /// # Returns
    /// `HashMap<String,f64>` - A hashmap containing the accuracy of the model. See the accuracy function in metrics for more details
    /// # Examples
    /// ```
    /// use rusty_math::linear::LogisticRegression;
    /// let mut model = LogisticRegression::new();
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let score = model.score(&x_test, &y_test);
    /// ```
    pub fn score(&self, x_test: &Vec<Vec<f64>>, y_test: &Vec<f64>) -> HashMap<String,f64>{
        let y_pred = self.predict(x_test);
        let y_test = y_test.iter().map(|&x| x as i32).collect();
        let y_pred = y_pred.iter().map(|&x| x as i32).collect();
        accuracy(&y_pred, &y_test)
    }

    /// Get the parameters of the model. The parameters are the weights and intercept. See the field descriptions for more information.
    /// The weights are stored in the HashMap with the key "weight_i" where i is the index of the weight.
    /// # Returns
    /// - `HashMap<String, String>` -  A HashMap containing the parameters of the model
    /// # Examples
    /// ```
    /// use rusty_math::linear::RidgeRegression;
    /// let mut model = RidgeRegression::new(0.01);
    /// model.fit(&x_train, &y_train, 0.01, 1000);
    /// let params = model.get_params();
    /// ```
    pub fn get_params(&self) -> HashMap<String, String> {
        let mut params = HashMap::new();
        params.insert("intercept".to_string(), self.intercept.to_string());
        for i in 0..self.weights.len() {
            params.insert(format!("weight_{}", i), self.weights[i].to_string());
        }
        params
    }

}



#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_linear_regression() {
        let mut model = LinearRegression::new();
        let x_train = vec![vec![1.0, 2.0], vec![2.0, 3.0], vec![3.0, 4.0]];
        let y_train = vec![3.0, 4.0, 5.0];
        model.fit(&x_train, &y_train, 0.01, 1000);
        let x_test = vec![vec![4.0, 5.0], vec![5.0, 6.0]];
        let y_pred = model.predict(&x_test);
        let score = model.score(&x_test, &vec![6.0, 7.0]);
        let coefficients = model.get_weights();
        let intercept = model.get_intercept();
    }

    #[test]
    fn test_polynomial_regression() {
        let mut model = PolynomialRegression::new(2);
        let x_train = vec![vec![1.0], vec![2.0], vec![3.0]];
        let y_train = vec![1.0, 4.0, 9.0];
        model.fit(&x_train, &y_train, 0.1, 1000);
        let x_test = vec![vec![4.0], vec![5.0]];
        let y_pred = model.predict(&x_test);
        let score = model.score(&x_test, &vec![16.0, 25.0]);
        let coefficients = model.get_weights();
        let intercept = model.get_intercept();
    }

    #[test]
    fn test_ridge_regression() {
        let mut model = RidgeRegression::new(0.01);
        let x_train = vec![vec![1.0, 2.0], vec![2.0, 3.0], vec![3.0, 4.0]];
        let y_train = vec![3.0, 4.0, 5.0];
        model.fit(&x_train, &y_train, 0.01, 1000);
        let x_test = vec![vec![4.0, 5.0], vec![5.0, 6.0]];
        let y_pred = model.predict(&x_test);
        let score = model.score(&x_test, &vec![6.0, 7.0]);
        let coefficients = model.get_weights();
        let intercept = model.get_intercept();
    }

    #[test]
    fn test_lasso_regression() {
        let mut model = LassoRegression::new(0.01);
        let x_train = vec![vec![1.0, 2.0], vec![1.0, 3.0], vec![1.0, 4.0]];
        let y_train = vec![3.0, 4.0, 5.0];
        model.fit(&x_train, y_train, 0.1, 1000);
        let x_test = vec![vec![1.0, 5.0], vec![1.0, 6.0]];
        let y_pred = model.predict(&x_test);
        let score = model.score(&x_test, &vec![6.0, 7.0]);
        let coefficients = model.weights();
        let intercept = model.intercept();
    }

    #[test]
    fn test_logistic_regression(){
        let x_train = vec![
            vec![1.0, 2.0],
            vec![2.0, 3.0],
            vec![3.0, 4.0],
            vec![4.0, 5.0],
            vec![5.0, 6.0],
            vec![6.0, 7.0],
        ];
        let y_train = vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
        let x_test = vec![vec![-1.0, 0.0], vec![4.0, 5.0], vec![7.0, 7.0], vec![1.0, 9.0]];
        let mut model = LogisticRegression::new();
        model.fit(&x_train, &y_train, 0.01, 1000);
        let preds = model.predict(&x_test);
        let score = model.score(&x_test, &vec![0.0, 1.0,1.0,0.0]);
        let weights = model.get_weights();
        let intercept = model.get_intercept();
    }
}