sklears-multioutput 0.1.1

Multi-output regression and classification
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
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
//! Sequence and structured prediction models
//!
//! This module provides algorithms for sequence labeling and structured prediction tasks.
//! It includes Hidden Markov Models (HMM), Structured Perceptron, and Maximum Entropy
//! Markov Models (MEMM) for handling sequential and structured data.
#![allow(non_snake_case)] // Standard ML notation: X for feature matrices, K for kernels

// Use SciRS2-Core for arrays and random number generation (SciRS2 Policy)
use scirs2_core::ndarray::{s, Array1, Array2, Array3, ArrayView1};
use scirs2_core::random::thread_rng;
use scirs2_core::random::RandNormal;
use sklears_core::{
    error::{Result as SklResult, SklearsError},
    traits::{Estimator, Fit, Predict, Untrained},
    types::Float,
};
use std::collections::{HashMap, HashSet};

/// Structured Perceptron for sequence labeling
///
/// The structured perceptron is an extension of the perceptron algorithm for
/// structured prediction problems. It can handle variable-length sequences and
/// complex output structures by using structured features and losses.
///
/// The structured perceptron extends the classic perceptron to handle structured
/// outputs by using a feature function that maps input-output pairs to feature
/// vectors and a loss function that measures the quality of predictions.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Predict, Fit};
/// use sklears_multioutput::StructuredPerceptron;
/// // Use SciRS2-Core for arrays and random number generation (SciRS2 Policy)
/// use scirs2_core::ndarray::array;
///
/// let X = array![[[1.0, 2.0], [2.0, 3.0]]]; // One sequence
/// let y = array![[0, 1]]; // Label sequence
///
/// let perceptron = StructuredPerceptron::new().max_iterations(50);
/// let trained_perceptron = perceptron.fit(&X, &y).unwrap();
/// let predictions = trained_perceptron.predict(&X).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct StructuredPerceptron<State = Untrained> {
    max_iterations: usize,
    learning_rate: Float,
    random_state: Option<u64>,
    state: State,
}

/// Trained state for Structured Perceptron
#[derive(Debug, Clone)]
pub struct StructuredPerceptronTrained {
    weights: Array1<Float>,
    n_features: usize,
    n_classes: usize,
}

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

impl StructuredPerceptron<Untrained> {
    /// Create a new Structured Perceptron
    pub fn new() -> Self {
        Self {
            max_iterations: 100,
            learning_rate: 1.0,
            random_state: None,
            state: Untrained,
        }
    }

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

    /// Set the learning rate
    pub fn learning_rate(mut self, learning_rate: Float) -> Self {
        self.learning_rate = learning_rate;
        self
    }

    /// Set the random state for reproducible results
    pub fn random_state(mut self, random_state: u64) -> Self {
        self.random_state = Some(random_state);
        self
    }
}

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

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

impl Fit<Array3<Float>, Array2<i32>> for StructuredPerceptron<Untrained> {
    type Fitted = StructuredPerceptron<StructuredPerceptronTrained>;

    fn fit(self, X: &Array3<Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_sequences, max_seq_len, n_features) = X.dim();

        if n_sequences != y.nrows() {
            return Err(SklearsError::InvalidInput(
                "X and y must have the same number of sequences".to_string(),
            ));
        }

        if y.ncols() != max_seq_len {
            return Err(SklearsError::InvalidInput(
                "y sequence length must match X sequence length".to_string(),
            ));
        }

        let n_classes = y.iter().max().unwrap_or(&0) + 1;
        let feature_dim = n_features * n_classes as usize + n_classes as usize * n_classes as usize;
        let mut weights = Array1::<Float>::zeros(feature_dim);

        let _rng = thread_rng();

        for _iteration in 0..self.max_iterations {
            let mut updated = false;

            for seq_idx in 0..n_sequences {
                let sequence = X.slice(s![seq_idx, .., ..]);
                let true_labels = y.row(seq_idx);

                // Simple prediction: take argmax for each position
                let mut predicted_labels = Array1::<Float>::zeros(max_seq_len);

                for pos in 0..max_seq_len {
                    let features = sequence.slice(s![pos, ..]);
                    let mut best_score = Float::NEG_INFINITY;
                    let mut best_label = 0;

                    for label in 0..n_classes {
                        let feature_offset = label as usize * n_features;
                        let score = features
                            .iter()
                            .enumerate()
                            .map(|(feat_idx, &feat_val)| {
                                weights[feature_offset + feat_idx] * feat_val
                            })
                            .sum::<Float>();

                        if score > best_score {
                            best_score = score;
                            best_label = label;
                        }
                    }
                    predicted_labels[pos] = best_label as Float;
                }

                // Check if prediction is correct
                let correct = true_labels
                    .iter()
                    .zip(predicted_labels.iter())
                    .all(|(&true_label, &pred_label)| true_label == pred_label as i32);

                if !correct {
                    // Update weights: add true features, subtract predicted features
                    for pos in 0..max_seq_len {
                        let features = sequence.slice(s![pos, ..]);
                        let true_label = true_labels[pos] as usize;
                        let pred_label = predicted_labels[pos] as usize;

                        // Add true label features
                        let true_offset = true_label * n_features;
                        for (feat_idx, &feat_val) in features.iter().enumerate() {
                            weights[true_offset + feat_idx] += self.learning_rate * feat_val;
                        }

                        // Subtract predicted label features
                        let pred_offset = pred_label * n_features;
                        for (feat_idx, &feat_val) in features.iter().enumerate() {
                            weights[pred_offset + feat_idx] -= self.learning_rate * feat_val;
                        }
                    }
                    updated = true;
                }
            }

            if !updated {
                break;
            }
        }

        Ok(StructuredPerceptron {
            max_iterations: self.max_iterations,
            learning_rate: self.learning_rate,
            random_state: self.random_state,
            state: StructuredPerceptronTrained {
                weights,
                n_features,
                n_classes: n_classes as usize,
            },
        })
    }
}

impl StructuredPerceptron<Untrained> {
    /// Get the weights of the trained model
    pub fn weights(&self) -> Option<&Array1<Float>> {
        None
    }
}

impl Predict<Array3<Float>, Array2<i32>> for StructuredPerceptron<StructuredPerceptronTrained> {
    fn predict(&self, X: &Array3<Float>) -> SklResult<Array2<i32>> {
        let (n_sequences, max_seq_len, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        let mut predictions = Array2::<i32>::zeros((n_sequences, max_seq_len));

        for seq_idx in 0..n_sequences {
            let sequence = X.slice(s![seq_idx, .., ..]);

            for pos in 0..max_seq_len {
                let features = sequence.slice(s![pos, ..]);
                let mut best_score = Float::NEG_INFINITY;
                let mut best_label = 0;

                for label in 0..self.state.n_classes {
                    let feature_offset = label * n_features;
                    let score = features
                        .iter()
                        .enumerate()
                        .map(|(feat_idx, &feat_val)| {
                            self.state.weights[feature_offset + feat_idx] * feat_val
                        })
                        .sum::<Float>();

                    if score > best_score {
                        best_score = score;
                        best_label = label;
                    }
                }
                predictions[[seq_idx, pos]] = best_label as i32;
            }
        }

        Ok(predictions)
    }
}

impl StructuredPerceptron<StructuredPerceptronTrained> {
    /// Get the weights of the trained model
    pub fn weights(&self) -> &Array1<Float> {
        &self.state.weights
    }
}

/// Hidden Markov Model for sequence modeling
///
/// A statistical model that assumes the system being modeled is a Markov process
/// with unobserved (hidden) states. HMMs are particularly useful for temporal
/// pattern recognition such as speech recognition, handwriting recognition,
/// gesture recognition, part-of-speech tagging, and bioinformatics.
///
/// # Examples
///
/// ```
/// use sklears_core::traits::{Predict, Fit};
/// use sklears_multioutput::HiddenMarkovModel;
/// // Use SciRS2-Core for arrays and random number generation (SciRS2 Policy)
/// use scirs2_core::ndarray::array;
///
/// let X = array![[[1.0, 2.0], [2.0, 3.0], [1.5, 2.5]]]; // One sequence
/// let y = array![[0, 1, 0]]; // State sequence
///
/// let hmm = HiddenMarkovModel::new().n_states(2).max_iterations(100);
/// let trained_hmm = hmm.fit(&X, &y).unwrap();
/// let predictions = trained_hmm.predict(&X).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct HiddenMarkovModel<State = Untrained> {
    n_states: usize,
    max_iterations: usize,
    tolerance: Float,
    random_state: Option<u64>,
    state: State,
}

/// Trained state for Hidden Markov Model
#[derive(Debug, Clone)]
pub struct HiddenMarkovModelTrained {
    transition_matrix: Array2<Float>,
    emission_means: Array2<Float>,
    #[allow(dead_code)]
    emission_covariances: Array3<Float>,
    initial_probs: Array1<Float>,
    n_features: usize,
    n_states: usize,
}

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

impl HiddenMarkovModel<Untrained> {
    /// Create a new Hidden Markov Model
    pub fn new() -> Self {
        Self {
            n_states: 2,
            max_iterations: 100,
            tolerance: 1e-6,
            random_state: None,
            state: Untrained,
        }
    }

    /// Set the number of hidden states
    pub fn n_states(mut self, n_states: usize) -> Self {
        self.n_states = n_states;
        self
    }

    /// Set the maximum number of iterations for EM algorithm
    pub fn max_iterations(mut self, max_iterations: usize) -> Self {
        self.max_iterations = max_iterations;
        self
    }

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

    /// Set the random state for reproducible results
    pub fn random_state(mut self, random_state: u64) -> Self {
        self.random_state = Some(random_state);
        self
    }
}

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

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

impl Fit<Array3<Float>, Array2<i32>> for HiddenMarkovModel<Untrained> {
    type Fitted = HiddenMarkovModel<HiddenMarkovModelTrained>;

    fn fit(self, X: &Array3<Float>, y: &Array2<i32>) -> SklResult<Self::Fitted> {
        let (n_sequences, max_seq_len, n_features) = X.dim();

        if n_sequences != y.nrows() {
            return Err(SklearsError::InvalidInput(
                "X and y must have the same number of sequences".to_string(),
            ));
        }

        if y.ncols() != max_seq_len {
            return Err(SklearsError::InvalidInput(
                "y sequence length must match X sequence length".to_string(),
            ));
        }

        let mut rng = thread_rng();

        // Initialize parameters
        let normal_dist = RandNormal::new(0.0, 1.0).expect("operation should succeed");
        let mut transition_matrix = Array2::<Float>::zeros((self.n_states, self.n_states));
        for i in 0..self.n_states {
            for j in 0..self.n_states {
                transition_matrix[[i, j]] = rng.sample(normal_dist);
            }
        }
        let mut emission_means = Array2::<Float>::zeros((self.n_states, n_features));
        for i in 0..self.n_states {
            for j in 0..n_features {
                emission_means[[i, j]] = rng.sample(normal_dist);
            }
        }
        let mut emission_covariances =
            Array3::from_elem((self.n_states, n_features, n_features), 1.0);
        let mut initial_probs = Array1::from_elem(self.n_states, 1.0 / self.n_states as Float);

        // Normalize transition matrix
        for i in 0..self.n_states {
            let row_sum = transition_matrix.row(i).sum();
            if row_sum > 0.0 {
                for j in 0..self.n_states {
                    transition_matrix[[i, j]] /= row_sum;
                }
            }
        }

        // Initialize emission covariances as identity matrices
        for state in 0..self.n_states {
            for i in 0..n_features {
                emission_covariances[[state, i, i]] = 1.0;
            }
        }

        let mut prev_likelihood = Float::NEG_INFINITY;

        // EM algorithm
        for _iteration in 0..self.max_iterations {
            // E-step: Forward-backward algorithm would go here
            // For simplicity, we'll use supervised learning with the provided labels

            // M-step: Update parameters based on state assignments
            let mut state_counts = Array1::<Float>::zeros(self.n_states);
            let mut transition_counts = Array2::<Float>::zeros((self.n_states, self.n_states));
            let mut emission_sums = Array2::<Float>::zeros((self.n_states, n_features));

            for seq_idx in 0..n_sequences {
                let sequence_data = X.slice(s![seq_idx, .., ..]);
                let sequence_states = y.row(seq_idx);

                for pos in 0..max_seq_len {
                    let state = sequence_states[pos] as usize;
                    if state < self.n_states {
                        state_counts[state] += 1.0;

                        // Update emission parameters
                        for feat in 0..n_features {
                            emission_sums[[state, feat]] += sequence_data[[pos, feat]];
                        }

                        // Update transition parameters
                        if pos < max_seq_len - 1 {
                            let next_state = sequence_states[pos + 1] as usize;
                            if next_state < self.n_states {
                                transition_counts[[state, next_state]] += 1.0;
                            }
                        }
                    }
                }

                // Update initial state probabilities
                let first_state = sequence_states[0] as usize;
                if first_state < self.n_states {
                    initial_probs[first_state] += 1.0;
                }
            }

            // Normalize and update parameters
            for state in 0..self.n_states {
                if state_counts[state] > 0.0 {
                    for feat in 0..n_features {
                        emission_means[[state, feat]] =
                            emission_sums[[state, feat]] / state_counts[state];
                    }
                }

                let row_sum = transition_counts.row(state).sum();
                if row_sum > 0.0 {
                    for next_state in 0..self.n_states {
                        transition_matrix[[state, next_state]] =
                            transition_counts[[state, next_state]] / row_sum;
                    }
                }
            }

            // Normalize initial probabilities
            let init_sum = initial_probs.sum();
            if init_sum > 0.0 {
                initial_probs /= init_sum;
            }

            // Simple likelihood calculation
            let total_likelihood = state_counts.sum() as Float;

            if (total_likelihood - prev_likelihood).abs() < self.tolerance {
                break;
            }
            prev_likelihood = total_likelihood;
        }

        Ok(HiddenMarkovModel {
            n_states: self.n_states,
            max_iterations: self.max_iterations,
            tolerance: self.tolerance,
            random_state: self.random_state,
            state: HiddenMarkovModelTrained {
                transition_matrix,
                emission_means,
                emission_covariances,
                initial_probs,
                n_features,
                n_states: self.n_states,
            },
        })
    }
}

impl HiddenMarkovModel<Untrained> {
    /// Get the transition matrix (only available after training)
    pub fn transition_matrix(&self) -> Option<&Array2<Float>> {
        None
    }

    /// Get the emission means (only available after training)
    pub fn emission_means(&self) -> Option<&Array2<Float>> {
        None
    }

    /// Get the initial state probabilities (only available after training)
    pub fn initial_probabilities(&self) -> Option<&Array1<Float>> {
        None
    }
}

impl Predict<Array3<Float>, Array2<i32>> for HiddenMarkovModel<HiddenMarkovModelTrained> {
    fn predict(&self, X: &Array3<Float>) -> SklResult<Array2<i32>> {
        let (n_sequences, max_seq_len, n_features) = X.dim();

        if n_features != self.state.n_features {
            return Err(SklearsError::InvalidInput(
                "X has different number of features than training data".to_string(),
            ));
        }

        let mut predictions = Array2::<i32>::zeros((n_sequences, max_seq_len));

        for seq_idx in 0..n_sequences {
            let sequence = X.slice(s![seq_idx, .., ..]);

            // Viterbi algorithm for finding most likely state sequence
            let mut viterbi = Array2::<Float>::zeros((max_seq_len, self.state.n_states));
            let mut path = Array2::<Float>::zeros((max_seq_len, self.state.n_states));

            // Initialize first time step
            for state in 0..self.state.n_states {
                let emission_prob = self.gaussian_probability(&sequence.slice(s![0, ..]), state);
                viterbi[[0, state]] = self.state.initial_probs[state].ln() + emission_prob.ln();
            }

            // Forward pass
            for t in 1..max_seq_len {
                for state in 0..self.state.n_states {
                    let emission_prob =
                        self.gaussian_probability(&sequence.slice(s![t, ..]), state);
                    let mut best_prob = Float::NEG_INFINITY;
                    let mut best_prev_state = 0;

                    for prev_state in 0..self.state.n_states {
                        let prob = viterbi[[t - 1, prev_state]]
                            + self.state.transition_matrix[[prev_state, state]].ln()
                            + emission_prob.ln();
                        if prob > best_prob {
                            best_prob = prob;
                            best_prev_state = prev_state;
                        }
                    }
                    viterbi[[t, state]] = best_prob;
                    path[[t, state]] = best_prev_state as Float;
                }
            }

            // Backward pass - find best path
            let mut states = Array1::<Float>::zeros(max_seq_len);

            // Find best final state
            let mut best_final_prob = Float::NEG_INFINITY;
            let mut best_final_state = 0;
            for state in 0..self.state.n_states {
                if viterbi[[max_seq_len - 1, state]] > best_final_prob {
                    best_final_prob = viterbi[[max_seq_len - 1, state]];
                    best_final_state = state;
                }
            }

            states[max_seq_len - 1] = best_final_state as Float;

            // Trace back
            for t in (0..max_seq_len - 1).rev() {
                states[t] = path[[t + 1, states[t + 1] as usize]];
            }

            // Copy to predictions
            for t in 0..max_seq_len {
                predictions[[seq_idx, t]] = states[t] as i32;
            }
        }

        Ok(predictions)
    }
}

impl HiddenMarkovModel<HiddenMarkovModelTrained> {
    /// Get the transition matrix
    pub fn transition_matrix(&self) -> &Array2<Float> {
        &self.state.transition_matrix
    }

    /// Get the emission means
    pub fn emission_means(&self) -> &Array2<Float> {
        &self.state.emission_means
    }

    /// Get the initial state probabilities
    pub fn initial_probabilities(&self) -> &Array1<Float> {
        &self.state.initial_probs
    }

    /// Calculate Gaussian probability for emission
    fn gaussian_probability(&self, observation: &ArrayView1<Float>, state: usize) -> Float {
        let mean = self.state.emission_means.row(state);
        let diff = observation.to_owned() - &mean.to_owned();

        // Simple Gaussian with identity covariance for now
        let exponent = -0.5 * diff.mapv(|x| x * x).sum();
        let normalization =
            (2.0 * std::f64::consts::PI).powf(self.state.n_features as f64 / 2.0) as Float;

        (exponent.exp() / normalization).max(1e-10)
    }
}

/// Maximum Entropy Markov Model (MEMM) for Sequence Labeling
///
/// MEMM is a discriminative model for sequence labeling that combines the advantages
/// of maximum entropy models with Markov assumptions. Unlike CRF, MEMM models the
/// conditional probability of each label given the previous label and observed features.
///
/// The model uses logistic regression at each position to predict the next label
/// based on features extracted from the current observation and previous label.
///
/// # Examples
///
/// ```
/// use sklears_multioutput::MaximumEntropyMarkovModel;
/// use sklears_core::traits::{Predict, Fit};
/// // Use SciRS2-Core for arrays and random number generation (SciRS2 Policy)
/// use scirs2_core::ndarray::array;
///
/// // Sequence data: each row is a sequence element with features
/// let X = vec![
///     array![[1.0, 2.0], [2.0, 3.0], [3.0, 1.0]], // sequence 1
///     array![[4.0, 1.0], [1.0, 4.0]]                // sequence 2
/// ];
///
/// // Label sequences
/// let y = vec![
///     vec![0, 1, 0], // labels for sequence 1
///     vec![1, 0]     // labels for sequence 2
/// ];
///
/// let memm = MaximumEntropyMarkovModel::new()
///     .max_iter(50)
///     .learning_rate(0.01);
/// let trained_memm = memm.fit(&X, &y).unwrap();
/// let predictions = trained_memm.predict(&X).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct MaximumEntropyMarkovModel<S = Untrained> {
    state: S,
    max_iter: usize,
    learning_rate: Float,
    l2_reg: Float,
    tolerance: Float,
    #[allow(dead_code)]
    feature_functions: Vec<FeatureFunction>,
    random_state: Option<u64>,
}

/// Trained state for MEMM
#[derive(Debug, Clone)]
pub struct MaximumEntropyMarkovModelTrained {
    weights: Array1<Float>,
    feature_functions: Vec<FeatureFunction>,
    n_labels: usize,
    n_features: usize,
    label_to_idx: HashMap<i32, usize>,
    #[allow(dead_code)]
    idx_to_label: HashMap<usize, i32>,
}

/// Feature function for MEMM
///
/// Each feature function extracts a specific type of feature from the input
/// and previous label combination. The feature value is typically binary
/// (0 or 1) indicating presence or absence of the feature.
#[derive(Debug, Clone)]
pub struct FeatureFunction {
    /// feature_type
    pub feature_type: FeatureType,
    /// weight_index
    pub weight_index: usize,
}

/// Types of features in MEMM
#[derive(Debug, Clone)]
pub enum FeatureType {
    /// Current observation feature at given index
    Observation(usize),
    /// Previous label feature
    PreviousLabel(i32),
    /// Interaction between observation and previous label
    LabelObservationInteraction(i32, usize),
}

impl MaximumEntropyMarkovModel<Untrained> {
    /// Create a new MEMM instance
    pub fn new() -> Self {
        Self {
            state: Untrained,
            max_iter: 100,
            learning_rate: 0.01,
            l2_reg: 0.01,
            tolerance: 1e-6,
            feature_functions: Vec::new(),
            random_state: None,
        }
    }

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

    /// Set learning rate
    pub fn learning_rate(mut self, learning_rate: Float) -> Self {
        self.learning_rate = learning_rate;
        self
    }

    /// Set L2 regularization strength
    pub fn l2_regularization(mut self, l2_reg: Float) -> Self {
        self.l2_reg = l2_reg;
        self
    }

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

    /// Set random state for reproducible results
    pub fn random_state(mut self, random_state: u64) -> Self {
        self.random_state = Some(random_state);
        self
    }
}

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

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

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

impl Fit<Vec<Array2<Float>>, Vec<Vec<i32>>> for MaximumEntropyMarkovModel<Untrained> {
    type Fitted = MaximumEntropyMarkovModel<MaximumEntropyMarkovModelTrained>;

    fn fit(self, X: &Vec<Array2<Float>>, y: &Vec<Vec<i32>>) -> SklResult<Self::Fitted> {
        if X.len() != y.len() {
            return Err(SklearsError::InvalidInput(
                "X and y must have the same number of sequences".to_string(),
            ));
        }

        if X.is_empty() {
            return Err(SklearsError::InvalidInput(
                "Cannot fit with 0 sequences".to_string(),
            ));
        }

        // Determine dimensions and create label mappings
        let n_features = X[0].ncols();
        let mut unique_labels = HashSet::new();

        for sequence_labels in y {
            for &label in sequence_labels {
                unique_labels.insert(label);
            }
        }

        let mut label_to_idx = HashMap::new();
        let mut idx_to_label = HashMap::new();
        // Sort labels to ensure deterministic ordering
        let mut sorted_labels: Vec<_> = unique_labels.iter().cloned().collect();
        sorted_labels.sort();
        for (idx, label) in sorted_labels.iter().enumerate() {
            label_to_idx.insert(*label, idx);
            idx_to_label.insert(idx, *label);
        }
        let n_labels = unique_labels.len();

        // Create feature functions
        let mut feature_functions = Vec::new();
        let mut weight_idx = 0;

        // Observation features
        for feat_idx in 0..n_features {
            for &label in &sorted_labels {
                feature_functions.push(FeatureFunction {
                    feature_type: FeatureType::LabelObservationInteraction(label, feat_idx),
                    weight_index: weight_idx,
                });
                weight_idx += 1;
            }
        }

        // Previous label features
        for &prev_label in &sorted_labels {
            for &_curr_label in &sorted_labels {
                feature_functions.push(FeatureFunction {
                    feature_type: FeatureType::PreviousLabel(prev_label),
                    weight_index: weight_idx,
                });
                weight_idx += 1;
            }
        }

        let n_weights = weight_idx;
        let mut weights = Array1::<Float>::zeros(n_weights);

        // Initialize weights randomly using random_state for reproducibility
        let mut rng = if let Some(seed) = self.random_state {
            scirs2_core::random::seeded_rng(seed)
        } else {
            // Use current time as seed for non-deterministic behavior
            use std::time::{SystemTime, UNIX_EPOCH};
            let time_seed = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .expect("operation should succeed")
                .as_secs();
            scirs2_core::random::seeded_rng(time_seed)
        };

        for w in weights.iter_mut() {
            *w = rng.gen_range(-0.1..0.1);
        }

        // Training loop
        for _iter in 0..self.max_iter {
            let mut gradient = Array1::<Float>::zeros(n_weights);
            let mut _total_loss = 0.0;

            // Process each sequence
            for (seq_idx, (sequence_x, sequence_y)) in X.iter().zip(y.iter()).enumerate() {
                let seq_len = sequence_x.nrows();

                if sequence_y.len() != seq_len {
                    return Err(SklearsError::InvalidInput(format!(
                        "Sequence {} length mismatch between X and y",
                        seq_idx
                    )));
                }

                // Process each position in the sequence
                for pos in 0..seq_len {
                    let current_obs = sequence_x.row(pos);
                    let true_label = sequence_y[pos];
                    let prev_label = if pos == 0 { -1 } else { sequence_y[pos - 1] };

                    // Calculate feature vector for current position
                    let _features =
                        self.extract_features(&current_obs, prev_label, &feature_functions);

                    // Calculate probabilities for all possible labels
                    let mut scores = Array1::<Float>::zeros(n_labels);
                    let mut max_score = Float::NEG_INFINITY;

                    for (label_idx, _label) in unique_labels.iter().enumerate() {
                        let label_features =
                            self.extract_features(&current_obs, prev_label, &feature_functions);
                        scores[label_idx] = label_features.dot(&weights);
                        max_score = max_score.max(scores[label_idx]);
                    }

                    // Numerical stability: subtract max score
                    for score in scores.iter_mut() {
                        *score -= max_score;
                    }

                    // Calculate softmax probabilities
                    let exp_scores: Array1<Float> = scores.mapv(|x| x.exp());
                    let sum_exp_scores = exp_scores.sum();
                    let probabilities = exp_scores / sum_exp_scores;

                    // Calculate loss (negative log likelihood)
                    let true_label_idx = label_to_idx[&true_label];
                    _total_loss -= probabilities[true_label_idx].ln();

                    // Calculate gradient
                    for (label_idx, _label) in sorted_labels.iter().enumerate() {
                        let label_features =
                            self.extract_features(&current_obs, prev_label, &feature_functions);
                        let prob = probabilities[label_idx];
                        let indicator = if label_idx == true_label_idx {
                            1.0
                        } else {
                            0.0
                        };

                        for (feat_idx, &feat_val) in label_features.iter().enumerate() {
                            gradient[feat_idx] += feat_val * (prob - indicator);
                        }
                    }
                }
            }

            // Add L2 regularization to gradient
            for (i, w) in weights.iter().enumerate() {
                gradient[i] += self.l2_reg * w;
            }

            // Update weights
            let gradient_norm = gradient.mapv(|x| x.abs()).sum();
            weights = &weights - self.learning_rate * &gradient;

            // Check convergence
            if gradient_norm < self.tolerance {
                break;
            }
        }

        let trained_state = MaximumEntropyMarkovModelTrained {
            weights,
            feature_functions,
            n_labels,
            n_features,
            label_to_idx,
            idx_to_label,
        };

        Ok(MaximumEntropyMarkovModel {
            state: trained_state,
            max_iter: self.max_iter,
            learning_rate: self.learning_rate,
            l2_reg: self.l2_reg,
            tolerance: self.tolerance,
            feature_functions: Vec::new(),
            random_state: self.random_state,
        })
    }
}

impl MaximumEntropyMarkovModel<Untrained> {
    /// Extract features for a given observation and previous label
    fn extract_features(
        &self,
        observation: &ArrayView1<Float>,
        prev_label: i32,
        feature_functions: &[FeatureFunction],
    ) -> Array1<Float> {
        let mut features = Array1::<Float>::zeros(feature_functions.len());

        for (i, func) in feature_functions.iter().enumerate() {
            features[i] = match &func.feature_type {
                FeatureType::Observation(feat_idx) => observation[*feat_idx],
                FeatureType::PreviousLabel(label) => {
                    if prev_label == *label {
                        1.0
                    } else {
                        0.0
                    }
                }
                FeatureType::LabelObservationInteraction(label, feat_idx) => {
                    if prev_label == *label {
                        observation[*feat_idx]
                    } else {
                        0.0
                    }
                }
            };
        }

        features
    }
}

impl Predict<Vec<Array2<Float>>, Vec<Vec<i32>>>
    for MaximumEntropyMarkovModel<MaximumEntropyMarkovModelTrained>
{
    fn predict(&self, X: &Vec<Array2<Float>>) -> SklResult<Vec<Vec<i32>>> {
        if X.is_empty() {
            return Ok(Vec::new());
        }

        let mut predictions = Vec::with_capacity(X.len());

        for sequence in X {
            let seq_len = sequence.nrows();

            if sequence.ncols() != self.state.n_features {
                return Err(SklearsError::InvalidInput(
                    "X has different number of features than training data".to_string(),
                ));
            }

            let mut sequence_predictions = Vec::with_capacity(seq_len);

            for pos in 0..seq_len {
                let current_obs = sequence.row(pos);
                let prev_label = if pos == 0 {
                    -1
                } else {
                    sequence_predictions[pos - 1]
                };

                // Calculate scores for all possible labels
                let mut best_score = Float::NEG_INFINITY;
                let mut best_label = 0;

                // Sort labels to ensure deterministic iteration order
                let mut labels_sorted: Vec<_> = self.state.label_to_idx.iter().collect();
                labels_sorted.sort_by_key(|(&label, _)| label);

                for (&label, &_label_idx) in labels_sorted {
                    let features = self.extract_features(
                        &current_obs,
                        prev_label,
                        &self.state.feature_functions,
                    );
                    let score = features.dot(&self.state.weights);

                    if score > best_score {
                        best_score = score;
                        best_label = label;
                    }
                }

                sequence_predictions.push(best_label);
            }

            predictions.push(sequence_predictions);
        }

        Ok(predictions)
    }
}

impl MaximumEntropyMarkovModel<MaximumEntropyMarkovModelTrained> {
    /// Get the learned weights
    pub fn weights(&self) -> &Array1<Float> {
        &self.state.weights
    }

    /// Get the number of labels
    pub fn n_labels(&self) -> usize {
        self.state.n_labels
    }

    /// Extract features for a given observation and previous label
    fn extract_features(
        &self,
        observation: &ArrayView1<Float>,
        prev_label: i32,
        feature_functions: &[FeatureFunction],
    ) -> Array1<Float> {
        let mut features = Array1::<Float>::zeros(feature_functions.len());

        for (i, func) in feature_functions.iter().enumerate() {
            features[i] = match &func.feature_type {
                FeatureType::Observation(feat_idx) => observation[*feat_idx],
                FeatureType::PreviousLabel(label) => {
                    if prev_label == *label {
                        1.0
                    } else {
                        0.0
                    }
                }
                FeatureType::LabelObservationInteraction(label, feat_idx) => {
                    if prev_label == *label {
                        observation[*feat_idx]
                    } else {
                        0.0
                    }
                }
            };
        }

        features
    }
}

#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
    use super::*;
    // Use SciRS2-Core for arrays and random number generation (SciRS2 Policy)
    use scirs2_core::ndarray::array;

    #[test]
    #[allow(non_snake_case)]
    fn test_structured_perceptron_basic() {
        let X = Array3::from_shape_vec((1, 2, 2), vec![1.0, 2.0, 2.0, 3.0])
            .expect("shape and data length should match");
        let y =
            Array2::from_shape_vec((1, 2), vec![0, 1]).expect("shape and data length should match");

        let perceptron = StructuredPerceptron::new().max_iterations(10);
        let trained = perceptron
            .fit(&X, &y)
            .expect("model fitting should succeed");
        let predictions = trained.predict(&X).expect("prediction should succeed");

        assert_eq!(predictions.dim(), (1, 2));
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_hidden_markov_model_basic() {
        let X = Array3::from_shape_vec((1, 3, 2), vec![1.0, 2.0, 2.0, 3.0, 1.5, 2.5])
            .expect("shape and data length should match");
        let y = Array2::from_shape_vec((1, 3), vec![0, 1, 0])
            .expect("shape and data length should match");

        let hmm = HiddenMarkovModel::new().n_states(2).max_iterations(5);
        let trained = hmm.fit(&X, &y).expect("model fitting should succeed");
        let predictions = trained.predict(&X).expect("prediction should succeed");

        assert_eq!(predictions.dim(), (1, 3));
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_memm_basic() {
        let X = vec![array![[1.0, 2.0], [2.0, 3.0]], array![[3.0, 1.0]]];
        let y = vec![vec![0, 1], vec![0]];

        let memm = MaximumEntropyMarkovModel::new()
            .max_iter(5)
            .learning_rate(0.1);
        let trained = memm.fit(&X, &y).expect("model fitting should succeed");
        let predictions = trained.predict(&X).expect("prediction should succeed");

        assert_eq!(predictions.len(), 2);
        assert_eq!(predictions[0].len(), 2);
        assert_eq!(predictions[1].len(), 1);
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_memm_reproducibility() {
        let X = vec![
            array![[1.0, 2.0], [2.0, 3.0]],
            array![[3.0, 1.0], [4.0, 2.0]],
        ];
        let y = vec![vec![0, 1], vec![1, 0]];

        let memm1 = MaximumEntropyMarkovModel::new()
            .max_iter(10)
            .random_state(42);
        let trained_memm1 = memm1.fit(&X, &y).expect("model fitting should succeed");
        let pred1 = trained_memm1
            .predict(&X)
            .expect("prediction should succeed");

        let memm2 = MaximumEntropyMarkovModel::new()
            .max_iter(10)
            .random_state(42);
        let trained_memm2 = memm2.fit(&X, &y).expect("model fitting should succeed");
        let pred2 = trained_memm2
            .predict(&X)
            .expect("prediction should succeed");

        assert_eq!(pred1, pred2);
    }
}