easy-ml 2.1.0

Machine learning library providing matrices, named tensors, linear algebra and automatic differentiation aimed at being easy to use
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
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
/*!
Naïve Bayes examples

# Naïve Bayes

The naïve bayes assumption is that all features in the labelled data are independent of each other
given the class they correspond to. This means the probability of some input given a class
can be computed as the product of each individual feature in that input conditioned on that class.

By Baye's Theorum we can relate the probability of the class given the input to the probability
of the input given the class. As a classifier only needs to determine which class some input
is most likely to be we can compare just the product of the probability of the input given a class
and the probability of that class.

## Bayes' Theorum

posterior = ( prior x likelihood ) / evidence

P(C<sub>k</sub> | **x**) = ( P(C<sub>k</sub>) * P(**x** | C<sub>k</sub>) ) / P(**x**)

P(C<sub>k</sub> | **x**) ∝ P(C<sub>k</sub>) * P(**x** | C<sub>k</sub>)

where C<sub>k</sub> is the kth class and **x** is the input to classify.

## Classifier

taking logs on Bayes' rule yields

log(P(C<sub>k</sub> | **x**)) ∝ log(P(C<sub>k</sub>)) + log(P(**x** | C<sub>k</sub>))

given the naïve bayes assumption

log(P(C<sub>k</sub> | **x**)) ∝ log(P(C<sub>k</sub>)) + the sum over all i features of (log(P(x<sub>i</sub> | C<sub>k</sub>)))

Then to determine the class we take the class corresponding to the largest
log(P(C<sub>k</sub> | **x**)).

Computing the individual probabilities of a feature conditioned on a class depends on what the
type of data is.

For categorical data this is simply occurances in class / total occurances. In practise laplacian
smoothing (adding one occurance for each class to the computed probabilities) may be used to
avoid computing a probability of 0 when some category doesn't have any samples for a class.

For continuous data we can model the feature as distributed according to a Gaussian distribution.

## Simple Naïve Bayes Example with F-1 score analysis

Naïve Bayes can be done by hand (with a calculator) which is what the below example will show.
We have a list of data about the environment and want to predict if we should go outside based
on the conditions. Some of these are categorical values and others are real valued.

```
use easy_ml::distributions::Gaussian;
use easy_ml::linear_algebra;

#[derive(Clone, Copy, PartialEq, Debug)]
enum Weather {
    Stormy, Rainy, Cloudy, Clear, Sunny
}

type WindSpeed = f64;

#[derive(Clone, Copy, PartialEq, Debug)]
enum Pandemic {
    Pandemic, NoPandemic
}

#[derive(Clone, Copy, PartialEq, Debug)]
enum Decision {
    GoOut, StayIn
}

#[derive(Clone, Copy, PartialEq, Debug)]
struct Observation {
    weather: Weather,
    wind: WindSpeed,
    pandemic: Pandemic,
    decision: Decision,
}

impl Observation {
    fn new(
    weather: Weather, wind: WindSpeed, pandemic: Pandemic, decision: Decision
) -> Observation {
        Observation {
            weather,
            wind,
            pandemic,
            decision
        }
    }
}

let observations = vec![
    Observation::new(Weather::Clear, 0.5, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Clear, 0.9, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Clear, 0.8, Pandemic::NoPandemic, Decision::StayIn),
    Observation::new(Weather::Stormy, 0.7, Pandemic::NoPandemic, Decision::StayIn),
    Observation::new(Weather::Rainy, 0.1, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Rainy, 0.5, Pandemic::NoPandemic, Decision::StayIn),
    Observation::new(Weather::Rainy, 0.6, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Rainy, 0.7, Pandemic::NoPandemic, Decision::StayIn),
    Observation::new(Weather::Cloudy, 0.3, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Cloudy, 0.5, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Cloudy, 0.2, Pandemic::NoPandemic, Decision::StayIn),
    Observation::new(Weather::Cloudy, 0.8, Pandemic::NoPandemic, Decision::StayIn),
    Observation::new(Weather::Sunny, 0.3, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Sunny, 0.9, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Sunny, 0.5, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Sunny, 0.5, Pandemic::NoPandemic, Decision::StayIn),
    Observation::new(Weather::Sunny, 0.5, Pandemic::Pandemic, Decision::StayIn),
    Observation::new(Weather::Clear, 0.1, Pandemic::Pandemic, Decision::StayIn),
    Observation::new(Weather::Clear, 0.9, Pandemic::Pandemic, Decision::StayIn)
];

fn predict(
    observations: &Vec<Observation>, weather: Weather, wind: WindSpeed, pandemic: Pandemic
) -> Decision {
    let total = observations.len() as f64;
    // first compute the number of each class in the data
    let total_stay_in = observations.iter()
        .filter(|observation| observation.decision == Decision::StayIn)
        .count() as f64;
    let total_go_out = observations.iter()
        .filter(|observation| observation.decision == Decision::GoOut)
        .count() as f64;

    let weather_log_probability_stay_in = {
        // compute how many rows in the data are this weather and stay in
        let total = observations.iter()
            .filter(|observation| observation.decision == Decision::StayIn)
            .filter(|observation| observation.weather == weather)
            .count() as f64;
        // there are 5 variants for the weather and we use laplacian smoothing
        // to avoid introducing zero probabilities, +1 / +5 treats the data
        // as if there is one stay in for each weather type.
        ((total + 1.0) / (total_stay_in + 5.0)).ln()
    };

    let weather_log_probability_go_out = {
        // compute how many rows in the data are this weather and go out
        let total = observations.iter()
            .filter(|observation| observation.decision == Decision::GoOut)
            .filter(|observation| observation.weather == weather)
            .count() as f64;
        // there are 5 variants for the weather and we use laplacian smoothing
        // to avoid introducing zero probabilities, +1 / +5 treats the data
        // as if there is one go out for each weather type.
        ((total + 1.0) / (total_go_out + 5.0)).ln()
    };

    // we're modelling the wind as a Gaussian so we get a probability by
    // computing the probability density for the wind we have, if it is
    // the same as the mean wind for stay in then it will be closest to 1
    // and the further away the closer to 0 it will be
    let wind_speed_model_stay_in: Gaussian<WindSpeed> = Gaussian::approximating(
        observations.iter()
        .filter(|observation| observation.decision == Decision::StayIn)
        .map(|observation| observation.wind)
    );
    let wind_log_probability_stay_in = wind_speed_model_stay_in.probability(&wind);

    let wind_speed_model_go_out: Gaussian<WindSpeed> = Gaussian::approximating(
        observations.iter()
        .filter(|observation| observation.decision == Decision::GoOut)
        .map(|observation| observation.wind)
    );
    let wind_log_probability_go_out = wind_speed_model_go_out.probability(&wind);

    let pandemic_log_probability_stay_in = {
        // compute how many rows in the data are this pandemic and stay in
        let total = observations.iter()
            .filter(|observation| observation.decision == Decision::StayIn)
            .filter(|observation| observation.pandemic == pandemic)
            .count() as f64;
        // there are 2 variants for the pandemic type and we use laplacian smoothing
        // to avoid introducing zero probabilities, +1 / +2 treats the data
        // as if there is one stay in for each pandemic type.
        ((total + 1.0) / (total_stay_in + 2.0)).ln()
    };

    let pandemic_log_probability_go_out = {
        // compute how many rows in the data are this pandemic and go out
        let total = observations.iter()
            .filter(|observation| observation.decision == Decision::GoOut)
            .filter(|observation| observation.pandemic == pandemic)
            .count() as f64;
        // there are 2 variants for the pandemic type and we use laplacian smoothing
        // to avoid introducing zero probabilities, +1 / +2 treats the data
        // as if there is one go out for each pandemic type.
        ((total + 1.0) / (total_go_out + 2.0)).ln()
    };

    let prior_log_probability_stay_in = total_stay_in / total;
    let prior_log_probability_go_out = total_go_out / total;

    let posterior_log_probability_stay_in = (
        prior_log_probability_stay_in
        + weather_log_probability_stay_in
        + wind_log_probability_stay_in
        + pandemic_log_probability_stay_in
    );
    let posterior_log_probability_go_out = (
        prior_log_probability_go_out
        + weather_log_probability_go_out
        + wind_log_probability_go_out
        + pandemic_log_probability_go_out
    );

    if posterior_log_probability_go_out > posterior_log_probability_stay_in {
        Decision::GoOut
    } else {
        Decision::StayIn
    }
}

let test_data = vec![
    Observation::new(Weather::Sunny, 0.8, Pandemic::NoPandemic, Decision::StayIn),
    Observation::new(Weather::Sunny, 0.2, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Stormy, 0.2, Pandemic::NoPandemic, Decision::StayIn),
    Observation::new(Weather::Cloudy, 0.3, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Rainy, 0.8, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Rainy, 0.5, Pandemic::NoPandemic, Decision::GoOut),
    Observation::new(Weather::Stormy, 0.6, Pandemic::Pandemic, Decision::StayIn),
    Observation::new(Weather::Rainy, 0.1, Pandemic::Pandemic, Decision::StayIn),
];

let predictions = test_data.iter()
    .map(|data| predict(&observations, data.weather, data.wind, data.pandemic))
    .collect::<Vec<Decision>>();

println!("Test data and predictions\n{:?}", test_data.iter()
    .cloned()
    .zip(predictions.clone())
    .collect::<Vec<(Observation, Decision)>>());

println!("Accuracy: {:?}", test_data.iter()
    .zip(predictions.clone())
    .map(|(data, decision)| if data.decision == decision { 1.0 } else { 0.0 })
    .sum::<f64>() / (test_data.len() as f64));

// To compute Recall and Precision it is neccessary to decide which class should be
// considered the positive and which should be the negative. For medical diagnosis
// this is always diagnosing something as present. For this example we take GoOut to
// be the positive case.

// True Positives are where the model predicts the positive class when it is
// the correct decision, eg in this scenario, going outside when it should
// decide to go outside
let true_positives = test_data.iter()
    .cloned()
    .zip(predictions.clone())
    .filter(|(data, _)| data.decision == Decision::GoOut)
    .filter(|(_, decision)| decision == &Decision::GoOut)
    .count() as f64;

// False Positives are when the model predicts the positive class when it is
// not the correct decision, eg in this scenario, going outside when it should
// decide to stay in
let false_positives = test_data.iter()
    .cloned()
    .zip(predictions.clone())
    .filter(|(data, _)| data.decision == Decision::StayIn)
    .filter(|(_, decision)| decision == &Decision::GoOut)
    .count() as f64;

// True Negatives are when the model predicts the negative class when it is
// the correct decision, eg in this scenario, staying in when it should
// decide to stay in
// there's a pandemic and no good reason to go outside
let true_negatives = test_data.iter()
    .cloned()
    .zip(predictions.clone())
    .filter(|(data, _)| data.decision == Decision::StayIn)
    .filter(|(_, decision)| decision == &Decision::StayIn)
    .count() as f64;

// False Negatives are when the model predicts the negative class when it is
// not the correct decision, eg in this scenario, staying in when it should
// decide to go outside
// there's a pandemic and no good reason to go outside
let false_negatives = test_data.iter()
    .cloned()
    .zip(predictions.clone())
    .filter(|(data, _)| data.decision == Decision::GoOut)
    .filter(|(_, decision)| decision == &Decision::StayIn)
    .count() as f64;

// Precision measures how good the model is at identifying the positive
// class (you can trivially get 100% precision by never predicting the
// positive class, as this means you can't get a false positive).
let precision = true_positives / (true_positives + false_positives);

// Recall is the true positive rate which is how good the model is at
// identifying the positive class out of all the positive cases (you can
// trivially get 100% recall by always predicting the positive class).
let recall = true_positives / (true_positives + false_negatives);

// The F-1 score is the harmonic mean of precision and recall and
// averages them for an accuracy measure.
// In this case the two classes are roughly equally likely, so the F-1
// score and Accuracy are similar. However, if the model had learned
// to always predict GoOut, then it would still have an accuracy of
// roughly 50% because of the equal likelihood, whereas its F-1 score
// would be much lower than 50%.
let f1_score = linear_algebra::f1_score(precision, recall);
println!("F1-Score: {:?}", f1_score);

assert!(f1_score > 0.8);
```

## 3 Class Naïve Bayes Example
[See submodule for 3 Class Naïve Bayes Example](three_class)
*/

#[rustfmt::skip]
pub mod three_class {
/*!
# 3 Class Naïve Bayes Example

For this example some population data is generated for a fictional alien race as I didn't
have any real datasets to hand. This alien race has 3 sexes (mysteriously no individuals
are ever intersex or trans) and is sexually dimorphic, meaning we can try to determine their
sex from various measuremnts.

As with humans, a gaussian distribution for physical charateristics is sensible due to
evolutionary and biological factors.

The example includes categorical features such as marking color and real valued
features such as height in order to show how both can be modelled with Naïve Bayes.

Note that most of the code below is for generating and clustering the data to perform
Naïve Bayes on, not doing it.

### Clustering

After generating the unlabelled data clustering is performed on a very small subset of that data
to find three cluster centres that are then used to assign the whole dataset sex class labels.
This creates a labelled dataset to perform Naïve Bayes on to see if we can predict sex given
the various features.

By clustering only a very small bit of the data, by chance we can expect there to be large gaps
in the subset because our data has many dimensions.

## Matrix APIs

```
use easy_ml::matrices::Matrix;
use easy_ml::matrices::views::{MatrixView, MatrixRange};
use easy_ml::linear_algebra;
use easy_ml::distributions::Gaussian;

use rand::{Rng, SeedableRng};
use rand::distr::{Iter, StandardUniform};
use rand_chacha::ChaCha8Rng;

#[derive(Clone, Copy, PartialEq, Debug)]
struct Alien {
    height: f64,
    primary_marking_color: AlienMarkingColor,
    tail_length: f64,
    metabolic_rate: f64,
    spiked_tail: bool,
    sex: AlienSex,
}

#[derive(Clone, Copy, Eq, PartialEq, Debug)]
enum AlienMarkingColor {
    Red = 1, Yellow, Orange, Blue, Purple, White, Black
}

#[derive(Clone, Copy, Eq, PartialEq, Debug)]
enum AlienSex {
    A, B, C
}

/**
 * ===============================
 * =       Data Generation       =
 * ===============================
 */

// rather than explicitly define a generative function that already knows the relationship
// between alien charateristics instead the samples are generated without an assigned sex
// and then clustered using k-means

// use a fixed seed random generator from the rand crate
let mut random_generator = ChaCha8Rng::seed_from_u64(16);
let mut random_numbers: Iter<StandardUniform, &mut ChaCha8Rng, f64> =
    (&mut random_generator).sample_iter(StandardUniform);

/**
 * Generates height data for creating the alien dataset.
 */
fn generate_heights(samples: usize, random_numbers: &mut impl Iterator<Item = f64>) -> Vec<f64> {
    // the average height shall be 1.5 meters with a standard deviation of 0.25
    let heights_distribution = Gaussian::new(1.5, 0.25 * 0.25);
    let mut heights = heights_distribution.draw(random_numbers, samples).unwrap();
    // ensure all aliens are at least 0.25 meters tall
    heights.drain(..).map(|x| x.max(0.25)).collect()
}

/**
 * Generates tail length data for creating the alien dataset.
 */
fn generate_tail_length(samples: usize, random_numbers: &mut impl Iterator<Item = f64>) -> Vec<f64> {
    // the average length shall be 1.25 meters with more variation in tail length
    let tails_distribution = Gaussian::new(1.25, 0.5 * 0.5);
    let mut tails = tails_distribution.draw(random_numbers, samples).unwrap();
    // ensure all tails are at least 0.5 meters long
    tails.drain(..).map(|x| if x > 0.5 { x } else { 0.5 }).collect()
}

/**
 * Generates color data for creating the alien dataset.
 *
 * Note that floats are still returned despite this being a category because we need all the
 * data types to be the same for clustering
 */
fn generate_colors(samples: usize, random_numbers: &mut impl Iterator<Item = f64>) -> Vec<f64> {
    let mut colors = Vec::with_capacity(samples);
    for i in 0..samples {
        let x = random_numbers.next().unwrap();
        if x < 0.2  {
            colors.push(AlienMarkingColor::Red as u8 as f64);
        } else if x < 0.3 {
            colors.push(AlienMarkingColor::Yellow as u8 as f64);
        } else if x < 0.45 {
            colors.push(AlienMarkingColor::Orange as u8 as f64);
        } else if x < 0.59 {
            colors.push(AlienMarkingColor::Blue as u8 as f64);
        } else if x < 0.63 {
            colors.push(AlienMarkingColor::Purple as u8 as f64);
        }  else if x < 0.9 {
            colors.push(AlienMarkingColor::White as u8 as f64);
        } else {
            colors.push(AlienMarkingColor::Black as u8 as f64);
        }
    }
    colors
}

/**
 * Recovers the color type which is the closest match to the input floating point color
 */
fn recover_generated_color(color: f64) -> AlienMarkingColor {
    let numerical_colors = [
        AlienMarkingColor::Red as u8 as f64,
        AlienMarkingColor::Yellow as u8 as f64,
        AlienMarkingColor::Orange as u8 as f64,
        AlienMarkingColor::Blue as u8 as f64,
        AlienMarkingColor::Purple as u8 as f64,
        AlienMarkingColor::White as u8 as f64,
        AlienMarkingColor::Black as u8 as f64,
    ];
    let colors = [
        AlienMarkingColor::Red,
        AlienMarkingColor::Yellow,
        AlienMarkingColor::Orange,
        AlienMarkingColor::Blue,
        AlienMarkingColor::Purple,
        AlienMarkingColor::White,
        AlienMarkingColor::Black,
    ];
    // look for the closest fit, as manipulated floating points may not be exact
    let color_index = numerical_colors.iter()
        // take the absolute difference so an exact match will become 0
        .map(|c| (c - color).abs())
        .enumerate()
        // find the element with the smallest difference in the list
        .min_by(|(_, a), (_, b)| a.partial_cmp(b).expect("NaN should not be in list"))
        // discard the difference
        .map(|(index, difference)| index)
        // retrieve the value from the option
        .unwrap();
    colors[color_index]
}

/**
 * Generates metabolic rate data for creating the alien dataset.
 */
fn generate_metabolic_rate(
    samples: usize, random_numbers: &mut impl Iterator<Item = f64>
) -> Vec<f64> {
    // the average rate shall be 100 heart beats per minute with a standard deviation of 20
    let metabolic_rate_distribution = Gaussian::new(100.0, 20.0 * 20.0);
    let mut metabolic_rates = metabolic_rate_distribution.draw(random_numbers, samples).unwrap();
    // ensure all rates are at least 50 and less than 200
    metabolic_rates.drain(..).map(|x| x.max(50.0).min(200.0)).collect()
}

/**
 * Generates spiked tailness data for creating the alien dataset.
 */
fn generate_spiked_tail(
    samples: usize, random_numbers: &mut impl Iterator<Item = f64>
) -> Vec<f64> {
    let mut spikes = Vec::with_capacity(samples);
    for i in 0..samples {
        let x = random_numbers.next().unwrap();
        if x < 0.4 {
            // 0 shall represent a non spiked tail
            spikes.push(0.0)
        } else {
            // 1 shall represent a spiked tail
            spikes.push(1.0)
        }
    }
    spikes
}

/**
 * Recovers the spiked tail type which is the closest match to the input floating point
 */
fn recover_generated_spiked_tail(spiked: f64) -> bool {
    return spiked >= 0.5
}

// We shall generate 1000 samples for the dataset
const SAMPLES: usize = 1000;

// Collect all the float typed features into a matrix
let unlabelled_dataset = {
    let mut dataset = Matrix::column(generate_heights(SAMPLES, &mut random_numbers));
    dataset.insert_column_with(1,
        generate_colors(SAMPLES, &mut random_numbers).drain(..));
    dataset.insert_column_with(2,
        generate_tail_length(SAMPLES, &mut random_numbers).drain(..));
    dataset.insert_column_with(3,
        generate_metabolic_rate(SAMPLES, &mut random_numbers).drain(..));
    dataset.insert_column_with(4,
        generate_spiked_tail(SAMPLES, &mut random_numbers).drain(..));
    dataset
};

/**
 * ===============================
 * =          Clustering         =
 * ===============================
 */

// Create a subset of the first 30 samples from the full dataset to use for clustering
let unlabelled_subset = MatrixView::from(
    MatrixRange::from(&unlabelled_dataset, 0..30, 0..unlabelled_dataset.columns())
);

// We normalise all the features to 0 mean and 1 standard deviation because
// we will use euclidean distance as the distance matric, and our features
// have very different variances. This avoids the distance metric being
// dominated by any particular feature.

let mut means_and_variances = Vec::with_capacity(unlabelled_subset.columns());

// The normalised subset is computed taking the mean and variance from the subset,
// these means and variances will be needed later to apply to the rest of the data.
let mut normalised_subset = {
    let mut normalised_subset = unlabelled_subset.map(|x| x);
    for feature in 0..normalised_subset.columns() {
        let mean = linear_algebra::mean(normalised_subset.column_iter(feature));
        let variance = linear_algebra::variance(normalised_subset.column_iter(feature));
        // save the data for normalisation and denormalisation for each feature
        // for use later
        means_and_variances.push(vec![ mean, variance ]);

        for row in 0..normalised_subset.rows() {
            let x = normalised_subset.get(row, feature);
            normalised_subset.set(row, feature, (x - mean) / variance);
        }
    }
    normalised_subset
};

// create a 5 x 2  matrix where each row is the mean and variance of each of the 5 features
let means_and_variances = Matrix::from(means_and_variances);

// pick the first 3 samples as the starting points for the cluster centres
// and place them into a 3 x 5 matrix where we have 3 rows of cluster centres
// and 5 features which are all normalised
let mut clusters = Matrix::from(vec![
    normalised_subset.row_iter(0).collect(),
    normalised_subset.row_iter(1).collect(),
    normalised_subset.row_iter(2).collect()]);

// add a 6th column to the subset to track the closest cluster for each sample
const CLUSTER_ID_COLUMN: usize = 5;
normalised_subset.insert_column(CLUSTER_ID_COLUMN, -1.0);

// set a threshold at which we consider the cluster centres to have converged
const CHANGE_THRESHOLD: f64 = 0.001;

// track how much the means have changed each update
let mut absolute_changes = -1.0;

// loop until we go under the CHANGE_THRESHOLD, reassigning points to the nearest
// cluster then cluster centres to their mean of points
while absolute_changes == -1.0 || absolute_changes > CHANGE_THRESHOLD {
    // assign each point to the nearest cluster centre by euclidean distance
    for point in 0..normalised_subset.rows() {
        let mut closest_cluster = -1.0;
        let mut least_squared_distance = std::f64::MAX;
        for cluster in 0..clusters.rows() {
            // we don't actually need to square root the distances for finding
            // which is least because least squared distance is the same as
            // least distance
            let squared_distance = {
                let mut sum = 0.0;
                for feature in 0..clusters.columns() {
                    let cluster_coordinate = clusters.get(cluster, feature);
                    let point_coordiante = normalised_subset.get(point, feature);
                    sum += (cluster_coordinate - point_coordiante).powi(2);
                }
                sum
            };

            if squared_distance < least_squared_distance {
                closest_cluster = cluster as f64;
                least_squared_distance = squared_distance;
            }
        }
        // save the cluster that is closest to each point in the 6th column
        normalised_subset.set(point, CLUSTER_ID_COLUMN, closest_cluster);
    }

    // update cluster centres to the mean of their points
    absolute_changes = 0.0;
    for cluster in 0..clusters.rows() {
        // construct a list of the points this cluster owns
        let owned = normalised_subset.column_iter(CLUSTER_ID_COLUMN)
            // zip together the id values with their index
            .enumerate()
            // exclude the points that aren't assigned to this cluster
            .filter(|(index, id)| (*id as usize) == cluster)
            // drop the cluster ids from each item and copy over the data
            // for each point for each feature
            .map(|(index, id)| {
                // for each point copy all its data in each feature excluding the
                // final cluster id column into a new vec
                normalised_subset.row_iter(index)
                    // taking the first 5 excludes the 6th column due to 0 indexing
                    .take(CLUSTER_ID_COLUMN)
                    .collect::<Vec<f64>>()
            })
            // collect into a vector of vectors containing each feature's data
            .collect::<Vec<Vec<f64>>>();
        // pass the vector of vectors into a matrix so we have
        // a matrix where each row is the data of a point this cluster owns
        let owned = Matrix::from(owned);

        // construct a vector of the mean for each feature that this cluster
        // now has
        let new_means = {
            let mut means = Vec::with_capacity(owned.rows());

            for feature in 0..owned.columns() {
                let mean = owned.column_iter(feature).sum::<f64>() / (owned.rows() as f64);
                means.push(mean);
            }

            means
        };

        // update each new mean for the cluster
        for feature in 0..clusters.columns() {
            let previous_mean = clusters.get(cluster, feature);
            // track the absolute difference between the new mean and the old one
            // so we know when to stop updating the clusters
            absolute_changes += (previous_mean - new_means[feature]).abs();

            println!(
                "Cluster {:?} mean for feature {:?} is now {:?} was {:?}",
                cluster, feature, new_means[feature], previous_mean
            );
            clusters.set(cluster, feature, new_means[feature]);
        }
    }
}

println!(
    "Denormalised clusters at convergence:\n{:?}\n{:.3}",
    vec![ "H", "C", "T", "M", "S" ],
    clusters.map_with_index(|x, _cluster, feature| {
        let mean = means_and_variances.get(feature, 0);
        let variance = means_and_variances.get(feature, 1);
        (x * variance) + mean
    }));

// Now we will assign every alien in the full dataset a sex using these cluster centres
let mut aliens: Vec<Alien> = Vec::with_capacity(unlabelled_dataset.rows());

fn assign_alien_sex(index: u8) -> AlienSex {
    if index == 0 {
        AlienSex::A
    } else if index == 1 {
        AlienSex::B
    } else {
        AlienSex::C
    }
}

for i in 0..unlabelled_dataset.rows() {
    let alien_data = Matrix::column(unlabelled_dataset.row_iter(i).collect());
    // normalise the alien data first so comparisons are on unit variance
    // and zero mean
    let normalised_alien_data = alien_data.map_with_index(|x, feature, _| {
        let mean = means_and_variances.get(feature, 0);
        let variance = means_and_variances.get(feature, 1);
        // normalise each feature in the alien data
        (x - mean) / variance
    });
    let mut distances = Vec::with_capacity(clusters.rows());
    for j in 0..clusters.rows() {
        let cluster_data = Matrix::row(clusters.row_iter(j).collect());
        // use euclidean distance to compare the alien with the cluster, the cluster
        // is already normalised
        let sum_of_squares = (cluster_data * &normalised_alien_data).scalar();
        distances.push(sum_of_squares);
    }

    // find the cluster with the lowest distance to each point and get its index
    let chosen_cluster = distances.iter()
        .enumerate()
        .min_by(|(_, a), (_, b)| a.partial_cmp(b).expect("NaN should not be in list"))
        .map(|(i, _)| i)
        .unwrap();

    // convert each float to the correct data type
    aliens.push(Alien {
        height: alien_data.get(0, 0),
        primary_marking_color: recover_generated_color(alien_data.get(1, 0)),
        tail_length: alien_data.get(2, 0),
        metabolic_rate: alien_data.get(3, 0),
        spiked_tail: recover_generated_spiked_tail(alien_data.get(4, 0)),
        sex: assign_alien_sex(chosen_cluster as u8),
    })
}

println!("First 10 aliens");
for i in 0..10 {
    println!("{:?}", aliens[i]);
}

// Put the aliens in a matrix for convenience
let aliens = Matrix::row(aliens);

println!("Sex A aliens total: {}", aliens.row_reference_iter(0)
    .fold(0, |accumulator, alien| accumulator + if alien.sex == AlienSex::A { 1 } else { 0 }));

println!("Sex B aliens total: {}", aliens.row_reference_iter(0)
    .fold(0, |accumulator, alien| accumulator + if alien.sex == AlienSex::B { 1 } else { 0 }));

println!("Sex C aliens total: {}", aliens.row_reference_iter(0)
    .fold(0, |accumulator, alien| accumulator + if alien.sex == AlienSex::C { 1 } else { 0 }));

/**
 * ===============================
 * =         Naïve Bayes         =
 * ===============================
 */

// Each class is roughly one third so we should not have a strong prior to a particular class

// In order to evaluate the performance of the Naïve Bayes classifier we will hold out
// the last 100 aliens from the dataset and use them as training data

let training_data = Matrix::column(aliens.row_iter(0).take(900).collect());
let test_data = Matrix::column(aliens.row_iter(0).skip(900).collect());

/**
 * Predicts the most probable alien sex for each test input alien (disregarding
 * the sex field in those inputs)
 *
 * For the real valued features the probabilities are computed by modelling
 * the features (conditioned on each class) as gaussian distributions.
 * For categorical features laplacian smoothing of the counts is used to
 * estimate probabilities of the features (conditioned on each class).
 */
fn predict_aliens(training_data: &Matrix<Alien>, test_data: &Matrix<Alien>) -> Matrix<AlienSex> {
    let mut relative_log_probabilities = Vec::with_capacity(3);

    for class in &[ AlienSex::A, AlienSex::B, AlienSex::C ] {
        let training_data_class_only = training_data.column_iter(0)
            .filter(|a| &a.sex == class)
            .collect::<Vec<Alien>>();

        // compute how likely each class is in the training set
        let prior = (training_data_class_only.len() as f64) / (training_data.rows() as f64);

        // We model the real valued features as Gaussians, note that these
        // are Gaussian distributions over only the training data of each class
        let heights: Gaussian<f64> = Gaussian::approximating(
            training_data_class_only.iter().map(|a| a.height)
        );
        let tail_lengths: Gaussian<f64> = Gaussian::approximating(
            training_data_class_only.iter().map(|a| a.tail_length)
        );
        let metabolic_rates: Gaussian<f64> = Gaussian::approximating(
            training_data_class_only.iter().map(|a| a.metabolic_rate)
        );

        // gradually build up the sum of log probabilities to get the
        // log of the prior * likelihood which will be proportional to the posterior
        let relative_log_probabilities_of_class = test_data.column_reference_iter(0)
        .map(|alien| {
            // probabilitiy of the alien sex and the alien
            let mut log_relative_probability = prior.ln();

            // Compute the probability using the Gaussian model for each real valued feature.
            // Due to floating point precision limits and the variance for some of these
            // Gaussian models being extremely small (0.01 for heights) we
            // check if a probability computed is zero or extremely close to zero
            // and if so increase it a bit to avoid computing -inf when we take the log.

            let mut height_given_class = heights.probability(&alien.height);
            if height_given_class.abs() <= 0.000000000001 {
                height_given_class = 0.000000000001;
            }
            log_relative_probability += height_given_class.ln();

            let mut tail_given_class = tail_lengths.probability(&alien.tail_length);
            if tail_given_class.abs() <= 0.000000000001 {
                tail_given_class = 0.000000000001;
            }
            log_relative_probability += tail_given_class.ln();

            let mut metabolic_rates_given_class = metabolic_rates.probability(
                &alien.metabolic_rate);
            if metabolic_rates_given_class.abs() <= 0.000000000001 {
                metabolic_rates_given_class = 0.000000000001;
            }
            log_relative_probability += metabolic_rates_given_class.ln();

            // compute the probability of the categorical features using lapacian smoothing
            let color_of_class = training_data_class_only.iter()
                .map(|a| a.primary_marking_color)
                // count how many aliens of this class have this color
                .fold(0, |acc, color|
                    acc + if color == alien.primary_marking_color { 1 } else { 0 });
            // with laplacian smoothing we assume there is one datapoint for each color
            // which avoids zero probabilities but does not distort the probabilities much
            // there are 7 color types so we add 7 to the total
            let color_given_class = ((color_of_class + 1) as f64)
                / ((training_data_class_only.len() + 7) as f64);
            log_relative_probability += color_given_class.ln();

            let spiked_tail_of_class = training_data_class_only.iter()
                .map(|a| a.spiked_tail)
                // count how many aliens of this class have a spiked tail or not
                .fold(0, |acc, spiked| acc + if spiked == alien.spiked_tail { 1 } else { 0 });
            // again we assume one alien of the class with a spiked tail and one without
            // to avoid zero probabilities
            let spiked_tail_given_class = ((spiked_tail_of_class + 1) as f64)
                / ((training_data_class_only.len() + 2) as f64);
            log_relative_probability += spiked_tail_given_class.ln();

            if log_relative_probability == std::f64::NEG_INFINITY {
                println!("Individual probs P:{} H:{} T:{} M:{} C:{} S:{}",
                    prior, height_given_class, tail_given_class, metabolic_rates_given_class,
                    color_given_class, spiked_tail_given_class);
            }

            log_relative_probability
        }).collect();

        relative_log_probabilities.push(relative_log_probabilities_of_class);
    }

    // collect the relative probabilitiy estimates for each class and each alien
    // into a 3 x 100 matrix respectively
    let probabilities = Matrix::from(relative_log_probabilities);

    let predictions = (0..probabilities.columns()).map(|i| {
        let predicted_class_index = probabilities.column_iter(i)
            .enumerate()
            // find the class with the highest relative probability estimate
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).expect("NaN should not be in list"))
            // discard the probability
            .map(|(index, p)| index)
            // retrieve the value from the option
            .unwrap();
        if predicted_class_index == 0 {
            AlienSex::A
        } else if predicted_class_index == 1 {
            AlienSex::B
        } else {
            AlienSex::C
        }
    }).collect();

    Matrix::column(predictions)
}

let predictions = predict_aliens(&training_data, &test_data);

println!("First 10 test aliens and predictions");
for i in 0..10 {
    println!("Predicted: {:?} Input: {:?}", predictions.get(i, 0), test_data.get(i, 0));
}

let accuracy = test_data.column_iter(0)
    .zip(predictions.column_iter(0))
    .map(|(alien, prediction)| if alien.sex == prediction { 1 } else { 0 })
    .sum::<u16>() as f64 / (test_data.rows() as f64);

println!("Accuracy {}%", accuracy * 100.0);

/**
 * ===============================
 * =           Analysis          =
 * ===============================
 */

// We can get a better sense of how well our classifier has done by
// printing the confusion matrix

// Construct a confusion matrix of actual x predicted classes, using A as 0, B as 1 and C as 2
// for indexing. If the accuracy was 100% we would see only non zero numbers on the diagonal
// as every prediction would be the actual class.
let confusion_matrix = {
    let mut confusion_matrix = Matrix::empty(0, (3, 3));

    // loop through all the actual and predicted classes to fill the confusion matrix
    // with the total occurances of each possible combination
    for (actual, predicted) in test_data.column_iter(0).zip(predictions.column_iter(0)) {
        match actual.sex {
            AlienSex::A => {
                match predicted {
                    AlienSex::A => confusion_matrix.set(0, 0, confusion_matrix.get(0, 0) + 1),
                    AlienSex::B => confusion_matrix.set(0, 1, confusion_matrix.get(0, 1) + 1),
                    AlienSex::C => confusion_matrix.set(0, 2, confusion_matrix.get(0, 2) + 1),
                }
            },
            AlienSex::B => {
                match predicted {
                    AlienSex::A => confusion_matrix.set(1, 0, confusion_matrix.get(1, 0) + 1),
                    AlienSex::B => confusion_matrix.set(1, 1, confusion_matrix.get(1, 1) + 1),
                    AlienSex::C => confusion_matrix.set(1, 2, confusion_matrix.get(1, 2) + 1),
                }
            },
            AlienSex::C => {
                match predicted {
                    AlienSex::A => confusion_matrix.set(2, 0, confusion_matrix.get(2, 0) + 1),
                    AlienSex::B => confusion_matrix.set(2, 1, confusion_matrix.get(2, 1) + 1),
                    AlienSex::C => confusion_matrix.set(2, 2, confusion_matrix.get(2, 2) + 1),
                }
            }
        }
    }

    confusion_matrix
};

println!("Confusion matrix: Rows are actual class, Columns are predicted class\n{}",
    confusion_matrix);
println!("  A  B  C");
```

## Tensor APIs


```
use easy_ml::tensors::Tensor;
use easy_ml::tensors::views::{TensorView, TensorStack};
use easy_ml::linear_algebra;
use easy_ml::distributions::Gaussian;

use rand::{Rng, SeedableRng};
use rand::distr::{Iter, StandardUniform};
use rand_chacha::ChaCha8Rng;

#[derive(Clone, Copy, PartialEq, Debug)]
struct Alien {
    height: f64,
    primary_marking_color: AlienMarkingColor,
    tail_length: f64,
    metabolic_rate: f64,
    spiked_tail: bool,
    sex: AlienSex,
}

#[derive(Clone, Copy, Eq, PartialEq, Debug)]
enum AlienMarkingColor {
    Red = 1, Yellow, Orange, Blue, Purple, White, Black
}

#[derive(Clone, Copy, Eq, PartialEq, Debug)]
enum AlienSex {
    A, B, C
}

/**
 * ===============================
 * =       Data Generation       =
 * ===============================
 */

// rather than explicitly define a generative function that already knows the relationship
// between alien charateristics instead the samples are generated without an assigned sex
// and then clustered using k-means

// use a fixed seed random generator from the rand crate
let mut random_generator = ChaCha8Rng::seed_from_u64(16);
let mut random_numbers: Iter<StandardUniform, &mut ChaCha8Rng, f64> =
    (&mut random_generator).sample_iter(StandardUniform);

/**
 * Generates height data for creating the alien dataset.
 */
fn generate_heights(samples: usize, random_numbers: &mut impl Iterator<Item = f64>) -> Vec<f64> {
    // the average height shall be 1.5 meters with a standard deviation of 0.25
    let heights_distribution = Gaussian::new(1.5, 0.25 * 0.25);
    let mut heights = heights_distribution.draw(random_numbers, samples).unwrap();
    // ensure all aliens are at least 0.25 meters tall
    heights.drain(..).map(|x| x.max(0.25)).collect()
}

/**
 * Generates tail length data for creating the alien dataset.
 */
fn generate_tail_length(samples: usize, random_numbers: &mut impl Iterator<Item = f64>) -> Vec<f64> {
    // the average length shall be 1.25 meters with more variation in tail length
    let tails_distribution = Gaussian::new(1.25, 0.5 * 0.5);
    let mut tails = tails_distribution.draw(random_numbers, samples).unwrap();
    // ensure all tails are at least 0.5 meters long
    tails.drain(..).map(|x| if x > 0.5 { x } else { 0.5 }).collect()
}

/**
 * Generates color data for creating the alien dataset.
 *
 * Note that floats are still returned despite this being a category because we need all the
 * data types to be the same for clustering
 */
fn generate_colors(samples: usize, random_numbers: &mut impl Iterator<Item = f64>) -> Vec<f64> {
    let mut colors = Vec::with_capacity(samples);
    for i in 0..samples {
        let x = random_numbers.next().unwrap();
        if x < 0.2  {
            colors.push(AlienMarkingColor::Red as u8 as f64);
        } else if x < 0.3 {
            colors.push(AlienMarkingColor::Yellow as u8 as f64);
        } else if x < 0.45 {
            colors.push(AlienMarkingColor::Orange as u8 as f64);
        } else if x < 0.59 {
            colors.push(AlienMarkingColor::Blue as u8 as f64);
        } else if x < 0.63 {
            colors.push(AlienMarkingColor::Purple as u8 as f64);
        }  else if x < 0.9 {
            colors.push(AlienMarkingColor::White as u8 as f64);
        } else {
            colors.push(AlienMarkingColor::Black as u8 as f64);
        }
    }
    colors
}

/**
 * Recovers the color type which is the closest match to the input floating point color
 */
fn recover_generated_color(color: f64) -> AlienMarkingColor {
    let numerical_colors = [
        AlienMarkingColor::Red as u8 as f64,
        AlienMarkingColor::Yellow as u8 as f64,
        AlienMarkingColor::Orange as u8 as f64,
        AlienMarkingColor::Blue as u8 as f64,
        AlienMarkingColor::Purple as u8 as f64,
        AlienMarkingColor::White as u8 as f64,
        AlienMarkingColor::Black as u8 as f64,
    ];
    let colors = [
        AlienMarkingColor::Red,
        AlienMarkingColor::Yellow,
        AlienMarkingColor::Orange,
        AlienMarkingColor::Blue,
        AlienMarkingColor::Purple,
        AlienMarkingColor::White,
        AlienMarkingColor::Black,
    ];
    // look for the closest fit, as manipulated floating points may not be exact
    let color_index = numerical_colors.iter()
        // take the absolute difference so an exact match will become 0
        .map(|c| (c - color).abs())
        .enumerate()
        // find the element with the smallest difference in the list
        .min_by(|(_, a), (_, b)| a.partial_cmp(b).expect("NaN should not be in list"))
        // discard the difference
        .map(|(index, difference)| index)
        // retrieve the value from the option
        .unwrap();
    colors[color_index]
}

/**
 * Generates metabolic rate data for creating the alien dataset.
 */
fn generate_metabolic_rate(
    samples: usize, random_numbers: &mut impl Iterator<Item = f64>
) -> Vec<f64> {
    // the average rate shall be 100 heart beats per minute with a standard deviation of 20
    let metabolic_rate_distribution = Gaussian::new(100.0, 20.0 * 20.0);
    let mut metabolic_rates = metabolic_rate_distribution.draw(random_numbers, samples).unwrap();
    // ensure all rates are at least 50 and less than 200
    metabolic_rates.drain(..).map(|x| x.max(50.0).min(200.0)).collect()
}

/**
 * Generates spiked tailness data for creating the alien dataset.
 */
fn generate_spiked_tail(
    samples: usize, random_numbers: &mut impl Iterator<Item = f64>
) -> Vec<f64> {
    let mut spikes = Vec::with_capacity(samples);
    for i in 0..samples {
        let x = random_numbers.next().unwrap();
        if x < 0.4 {
            // 0 shall represent a non spiked tail
            spikes.push(0.0)
        } else {
            // 1 shall represent a spiked tail
            spikes.push(1.0)
        }
    }
    spikes
}

/**
 * Recovers the spiked tail type which is the closest match to the input floating point
 */
fn recover_generated_spiked_tail(spiked: f64) -> bool {
    return spiked >= 0.5
}

// We shall generate 1000 samples for the dataset
const SAMPLES: usize = 1000;

// Each sample has 5 features
const FEATURES: usize = 5;

// Collect all the float typed features into a 2 dimensional tensor of samples x data
let unlabelled_dataset = {
    let heights = Tensor::from(
        [("sample", SAMPLES)], generate_heights(SAMPLES, &mut random_numbers)
    );
    let colours = Tensor::from(
        [("sample", SAMPLES)], generate_colors(SAMPLES, &mut random_numbers)
    );
    let tail_lengths = Tensor::from(
        [("sample", SAMPLES)], generate_tail_length(SAMPLES, &mut random_numbers)
    );
    let metabolic_rates = Tensor::from(
        [("sample", SAMPLES)], generate_metabolic_rate(SAMPLES, &mut random_numbers)
    );
    let spiked_tail = Tensor::from(
        [("sample", SAMPLES)], generate_spiked_tail(SAMPLES, &mut random_numbers)
    );

    TensorView::from(
        TensorStack::<_, [_; 5], 1>::from(
            [ heights, colours, tail_lengths, metabolic_rates, spiked_tail ],
            // we stack along the second axis that we're creating to get our rows of samples
            // this leaves the existing axis in all our individual column vectors to be each
            // feature's data
            (1, "feature")
        )
    )
};

/**
 * ===============================
 * =          Clustering         =
 * ===============================
 */

// Create a subset of the first 30 samples from the full dataset to use for clustering
const SUBSET_SAMPLES: usize = 30;
let unlabelled_subset = unlabelled_dataset.range([("sample", 0..SUBSET_SAMPLES)])
    .expect("The unlabelled data set should have at least 30 samples");

// We normalise all the features to 0 mean and 1 standard deviation because
// we will use euclidean distance as the distance matric, and our features
// have very different variances. This avoids the distance metric being
// dominated by any particular feature.

let mut means_and_variances = Vec::with_capacity(FEATURES);

// The normalised subset is computed taking the mean and variance from the subset,
// these means and variances will be needed later to apply to the rest of the data.
let mut normalised_subset = {
    let mut normalised_subset = unlabelled_subset.map(|x| x);
    for feature in 0..FEATURES {
        let mut feature_data = normalised_subset.select_mut([("feature", feature)]);
        let mean = linear_algebra::mean(feature_data.iter());
        let variance = linear_algebra::variance(feature_data.iter());
        // save the data for normalisation and denormalisation for each feature
        // for use later
        means_and_variances.push((mean, variance));

        for (row, x) in feature_data.iter_reference_mut().enumerate() {
            *x = (*x - mean) / variance;
        }
    }
    normalised_subset
};

// create a tensor where each row is a tuple of the mean and variance of each of the
// 5 features
let means_and_variances = Tensor::from([("feature", FEATURES)], means_and_variances);

// pick the first 3 samples as the starting points for the cluster centres
// and place them into a 3 x 5 tensor where we have 3 rows of cluster centres
// and 5 features which are all normalised
const CLUSTERS: usize = 3;
let mut clusters = TensorView::from(
    TensorStack::<_, [_; 3], 1>::from(
        [
            normalised_subset.select([("sample", 0)]).source(),
            normalised_subset.select([("sample", 1)]).source(),
            normalised_subset.select([("sample", 2)]).source()
        ],
        (0, "cluster")
    )
).map(|x| x);

// add a 6th column to the subset to track the closest cluster for each sample
const CLUSTER_ID_COLUMN: usize = 5;
let mut normalised_subset = {
    let mut data = normalised_subset.iter();
    let mut tensor = Tensor::empty([("sample", SUBSET_SAMPLES), ("feature", FEATURES + 1)], -1.0);
    for ([_row, feature], x) in tensor.iter_reference_mut().with_index() {
        *x = match feature {
            0 | 1 | 2 | 3 | 4 => data.next().unwrap(),
            _ => -1.0
        };
    }
    tensor
};

// set a threshold at which we consider the cluster centres to have converged
const CHANGE_THRESHOLD: f64 = 0.001;

// track how much the means have changed each update
let mut absolute_changes = -1.0;

// loop until we go under the CHANGE_THRESHOLD, reassigning points to the nearest
// cluster then cluster centres to their mean of points
while absolute_changes == -1.0 || absolute_changes > CHANGE_THRESHOLD {
    // assign each point to the nearest cluster centre by euclidean distance
    for point in 0..SUBSET_SAMPLES {
        let mut closest_cluster = -1.0;
        let mut least_squared_distance = std::f64::MAX;
        let clusters_indexing = clusters.index();
        let mut samples_indexing = normalised_subset.index_mut();
        for cluster in 0..CLUSTERS {
            // we don't actually need to square root the distances for finding
            // which is least because least squared distance is the same as
            // least distance
            let squared_distance = {
                let mut sum = 0.0;

                for feature in 0..FEATURES {
                    let cluster_coordinate = clusters_indexing.get([cluster, feature]);
                    let point_coordiante = samples_indexing.get([point, feature]);
                    sum += (cluster_coordinate - point_coordiante).powi(2);
                }
                sum
            };

            if squared_distance < least_squared_distance {
                closest_cluster = cluster as f64;
                least_squared_distance = squared_distance;
            }
        }
        // save the cluster that is closest to each point in the 6th column
        *samples_indexing.get_ref_mut([point, CLUSTER_ID_COLUMN]) = closest_cluster;
    }

    // update cluster centres to the mean of their points
    absolute_changes = 0.0;
    for cluster in 0..CLUSTERS {
        // construct a list of the points this cluster owns
        let owned = normalised_subset.select([("feature", CLUSTER_ID_COLUMN)]).iter()
            // zip together the id values with their index
            .enumerate()
            // exclude the points that aren't assigned to this cluster
            .filter(|(index, id)| (*id as usize) == cluster)
            // drop the cluster ids from each item and copy over the data
            // for each point for each feature
            .map(|(index, id)| {
                // for each point copy all its data in each feature excluding the
                // final cluster id column into a new vec
                normalised_subset.select([("sample", index)]).iter()
                    // taking the first 5 excludes the 6th column due to 0 indexing
                    .take(CLUSTER_ID_COLUMN)
                    .collect::<Vec<f64>>()
            })
            // collect into a vector of vectors containing each feature's data
            .collect::<Vec<Vec<f64>>>();
        // pass the vector of vectors into a tensor so we have
        // a tensor where each row is the data of a point this cluster owns
        let owned_points = owned.len();
        let owned = Tensor::from([("owned", owned.len())], owned);

        // construct a vector of the mean for each feature that this cluster
        // now has
        let new_means = {
            let mut means = Vec::with_capacity(owned_points);

            for feature in 0..FEATURES {
                let mean = owned.iter().map(|x| x[feature]).sum::<f64>() / (owned_points as f64);
                means.push(mean);
            }

            means
        };

        // update each new mean for the cluster
        for feature in 0..FEATURES {
            let mut clusters_indexing = clusters.index_mut();
            let previous_mean = clusters_indexing.get([cluster, feature]);
            // track the absolute difference between the new mean and the old one
            // so we know when to stop updating the clusters
            absolute_changes += (previous_mean - new_means[feature]).abs();

            println!(
                "Cluster {:?} mean for feature {:?} is now {:?} was {:?}",
                cluster, feature, new_means[feature], previous_mean
            );
            *clusters_indexing.get_ref_mut([cluster, feature]) = new_means[feature];
        }
    }
}

println!(
    "Denormalised clusters at convergence:\n{:?}\n{:.3}",
    vec![ "H", "C", "T", "M", "S" ],
    clusters.map_with_index(|[_cluster, feature], x| {
        let indexing = means_and_variances.index();
        let (mean, variance) = indexing.get([feature]);
        (x * variance) + mean
    }));

// Now we will assign every alien in the full dataset a sex using these cluster centres
let mut aliens: Vec<Alien> = Vec::with_capacity(SAMPLES);

fn assign_alien_sex(index: u8) -> AlienSex {
    if index == 0 {
        AlienSex::A
    } else if index == 1 {
        AlienSex::B
    } else {
        AlienSex::C
    }
}

for i in 0..SAMPLES {
    let alien_data = unlabelled_dataset.select([("sample", i)]).map(|x| x);
    // normalise the alien data first so comparisons are on unit variance
    // and zero mean
    let normalised_alien_data = alien_data.map_with_index(|[feature], x| {
        let indexing = means_and_variances.index();
        let (mean, variance) = indexing.get([feature]);
        // normalise each feature in the alien data
        (x - mean) / variance
    });
    let mut distances = Vec::with_capacity(CLUSTERS);
    for j in 0..CLUSTERS {
        let cluster_data = clusters.select([("cluster", j)]);
        // use euclidean distance to compare the alien with the cluster, the cluster
        // is already normalised
        // we have a 1 x 5 tensor for cluser data and a 5 x 1 tensor for alien data so matrix
        // multiplication here gives us the sum of products
        let sum_of_squares = (
            cluster_data.expand([(0, "samples")]) * normalised_alien_data.expand([(1, "alien")])
        ).first();
        distances.push(sum_of_squares);
    }

    // find the cluster with the lowest distance to each point and get its index
    let chosen_cluster = distances.iter()
        .enumerate()
        .min_by(|(_, a), (_, b)| a.partial_cmp(b).expect("NaN should not be in list"))
        .map(|(i, _)| i)
        .unwrap();

    // convert each float to the correct data type
    let alien_data_indexing = alien_data.index();
    aliens.push(Alien {
        height: alien_data_indexing.get([0]),
        primary_marking_color: recover_generated_color(alien_data_indexing.get([1])),
        tail_length: alien_data_indexing.get([2]),
        metabolic_rate: alien_data_indexing.get([3]),
        spiked_tail: recover_generated_spiked_tail(alien_data_indexing.get([4])),
        sex: assign_alien_sex(chosen_cluster as u8),
    })
}

println!("First 10 aliens");
for i in 0..10 {
    println!("{:?}", aliens[i]);
}

// Put the aliens in a tensor for convenience
let aliens = Tensor::from([("sample", SAMPLES)], aliens);

println!("Sex A aliens total: {}", aliens.iter_reference()
    .fold(0, |accumulator, alien| accumulator + if alien.sex == AlienSex::A { 1 } else { 0 }));

println!("Sex B aliens total: {}", aliens.iter_reference()
    .fold(0, |accumulator, alien| accumulator + if alien.sex == AlienSex::B { 1 } else { 0 }));

println!("Sex C aliens total: {}", aliens.iter_reference()
    .fold(0, |accumulator, alien| accumulator + if alien.sex == AlienSex::C { 1 } else { 0 }));

/**
 * ===============================
 * =         Naïve Bayes         =
 * ===============================
 */

// Each class is roughly one third so we should not have a strong prior to a particular class

// In order to evaluate the performance of the Naïve Bayes classifier we will hold out
// the last 100 aliens from the dataset and use them as training data

const TRAINING_SAMPLES: usize = 900;
const TESTING_SAMPLES: usize = 100;
let training_data = Tensor::from([("sample", 900)], aliens.iter().take(TRAINING_SAMPLES).collect());
let test_data = Tensor::from([("sample", 100)], aliens.iter().skip(TRAINING_SAMPLES).collect());

/**
 * Predicts the most probable alien sex for each test input alien (disregarding
 * the sex field in those inputs)
 *
 * For the real valued features the probabilities are computed by modelling
 * the features (conditioned on each class) as gaussian distributions.
 * For categorical features laplacian smoothing of the counts is used to
 * estimate probabilities of the features (conditioned on each class).
 */
fn predict_aliens(training_data: &Tensor<Alien, 1>, test_data: &Tensor<Alien, 1>) -> Tensor<AlienSex, 1> {
    let mut relative_log_probabilities: Vec<f64> = Vec::with_capacity(300);

    for class in &[ AlienSex::A, AlienSex::B, AlienSex::C ] {
        let training_data_class_only = training_data.iter()
            .filter(|a| &a.sex == class)
            .collect::<Vec<Alien>>();

        // compute how likely each class is in the training set
        let prior = (training_data_class_only.len() as f64) / (TRAINING_SAMPLES as f64);

        // We model the real valued features as Gaussians, note that these
        // are Gaussian distributions over only the training data of each class
        let heights: Gaussian<f64> = Gaussian::approximating(
            training_data_class_only.iter().map(|a| a.height)
        );
        let tail_lengths: Gaussian<f64> = Gaussian::approximating(
            training_data_class_only.iter().map(|a| a.tail_length)
        );
        let metabolic_rates: Gaussian<f64> = Gaussian::approximating(
            training_data_class_only.iter().map(|a| a.metabolic_rate)
        );

        // gradually build up the sum of log probabilities to get the
        // log of the prior * likelihood which will be proportional to the posterior
        let mut relative_log_probabilities_of_class = test_data.iter_reference()
        .map(|alien| {
            // probabilitiy of the alien sex and the alien
            let mut log_relative_probability = prior.ln();

            // Compute the probability using the Gaussian model for each real valued feature.
            // Due to floating point precision limits and the variance for some of these
            // Gaussian models being extremely small (0.01 for heights) we
            // check if a probability computed is zero or extremely close to zero
            // and if so increase it a bit to avoid computing -inf when we take the log.

            let mut height_given_class = heights.probability(&alien.height);
            if height_given_class.abs() <= 0.000000000001 {
                height_given_class = 0.000000000001;
            }
            log_relative_probability += height_given_class.ln();

            let mut tail_given_class = tail_lengths.probability(&alien.tail_length);
            if tail_given_class.abs() <= 0.000000000001 {
                tail_given_class = 0.000000000001;
            }
            log_relative_probability += tail_given_class.ln();

            let mut metabolic_rates_given_class = metabolic_rates.probability(
                &alien.metabolic_rate);
            if metabolic_rates_given_class.abs() <= 0.000000000001 {
                metabolic_rates_given_class = 0.000000000001;
            }
            log_relative_probability += metabolic_rates_given_class.ln();

            // compute the probability of the categorical features using lapacian smoothing
            let color_of_class = training_data_class_only.iter()
                .map(|a| a.primary_marking_color)
                // count how many aliens of this class have this color
                .fold(0, |acc, color|
                    acc + if color == alien.primary_marking_color { 1 } else { 0 });
            // with laplacian smoothing we assume there is one datapoint for each color
            // which avoids zero probabilities but does not distort the probabilities much
            // there are 7 color types so we add 7 to the total
            let color_given_class = ((color_of_class + 1) as f64)
                / ((training_data_class_only.len() + 7) as f64);
            log_relative_probability += color_given_class.ln();

            let spiked_tail_of_class = training_data_class_only.iter()
                .map(|a| a.spiked_tail)
                // count how many aliens of this class have a spiked tail or not
                .fold(0, |acc, spiked| acc + if spiked == alien.spiked_tail { 1 } else { 0 });
            // again we assume one alien of the class with a spiked tail and one without
            // to avoid zero probabilities
            let spiked_tail_given_class = ((spiked_tail_of_class + 1) as f64)
                / ((training_data_class_only.len() + 2) as f64);
            log_relative_probability += spiked_tail_given_class.ln();

            if log_relative_probability == std::f64::NEG_INFINITY {
                println!("Individual probs P:{} H:{} T:{} M:{} C:{} S:{}",
                    prior, height_given_class, tail_given_class, metabolic_rates_given_class,
                    color_given_class, spiked_tail_given_class);
            }

            log_relative_probability
        }).collect();

        relative_log_probabilities.append(&mut relative_log_probabilities_of_class);
    }

    // collect the relative probabilitiy estimates for each class and each alien
    // into a 3 x 100 matrix respectively
    let probabilities = Tensor::from([("class", 3), ("sample", 100)], relative_log_probabilities);

    let predictions = (0..100).map(|i| {
        let predicted_class_index = probabilities.select([("sample", i)])
            .iter()
            .enumerate()
            // find the class with the highest relative probability estimate
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).expect("NaN should not be in list"))
            // discard the probability
            .map(|(index, p)| index)
            // retrieve the value from the option
            .unwrap();
        if predicted_class_index == 0 {
            AlienSex::A
        } else if predicted_class_index == 1 {
            AlienSex::B
        } else {
            AlienSex::C
        }
    }).collect();

    Tensor::from([("class", 100)], predictions)
}

let predictions = predict_aliens(&training_data, &test_data);

println!("First 10 test aliens and predictions");
for i in 0..10 {
    println!("Predicted: {:?} Input: {:?}", predictions.index().get([i]), test_data.index().get([i]));
}

let accuracy = test_data.iter_reference()
    .zip(predictions.iter_reference())
    .map(|(alien, prediction)| if alien.sex == *prediction { 1 } else { 0 })
    .sum::<u16>() as f64 / (TESTING_SAMPLES as f64);

println!("Accuracy {}%", accuracy * 100.0);

/**
 * ===============================
 * =           Analysis          =
 * ===============================
 */

// We can get a better sense of how well our classifier has done by
// printing the confusion matrix

// Construct a confusion matrix of actual x predicted classes, using A as 0, B as 1 and C as 2
// for indexing. If the accuracy was 100% we would see only non zero numbers on the diagonal
// as every prediction would be the actual class.
let confusion_matrix = {
    let mut confusion_matrix = Tensor::empty([("actual_class", 3), ("predicted_class", 3)], 0);
    let mut confusion_matrix_indexing = confusion_matrix.index_mut();

    // loop through all the actual and predicted classes to fill the confusion matrix
    // with the total occurances of each possible combination
    for (actual, predicted) in test_data.iter_reference().zip(predictions.iter_reference()) {
        match actual.sex {
            AlienSex::A => {
                match predicted {
                    AlienSex::A => *confusion_matrix_indexing.get_ref_mut([0, 0]) += 1,
                    AlienSex::B => *confusion_matrix_indexing.get_ref_mut([0, 1]) += 1,
                    AlienSex::C => *confusion_matrix_indexing.get_ref_mut([0, 2]) += 1,
                }
            },
            AlienSex::B => {
                match predicted {
                    AlienSex::A => *confusion_matrix_indexing.get_ref_mut([1, 0]) += 1,
                    AlienSex::B => *confusion_matrix_indexing.get_ref_mut([1, 1]) += 1,
                    AlienSex::C => *confusion_matrix_indexing.get_ref_mut([1, 2]) += 1,
                }
            },
            AlienSex::C => {
                match predicted {
                    AlienSex::A => *confusion_matrix_indexing.get_ref_mut([2, 0]) += 1,
                    AlienSex::B => *confusion_matrix_indexing.get_ref_mut([2, 1]) += 1,
                    AlienSex::C => *confusion_matrix_indexing.get_ref_mut([2, 2]) += 1,
                }
            }
        }
    }

    confusion_matrix
};

println!("Confusion matrix: Rows are actual class, Columns are predicted class\n{}",
    confusion_matrix);
println!("  A  B  C");
```

The above code prints 60% accuracy which isn't amazing as if we learned the cluster centers
that labelled the data in the first place we should be able to get 100% accuracy but
60% is still far better than guessing for a three class problem. As Naïve Bayes has no
hyperparameters it is good for establishing a good baseline to compare other examples such
as [Logistic Regression](super::super::logistic_regression) to.
*/

}