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
use std::fmt::Display;
use std::path::Path;
use std::str::FromStr;
use std::time::Instant;
use ndarray::prelude::*;
use ndarray::Array;
use crate::activation::{activate, activate_der, ActivationType};
use crate::dataset::Dataset;
use crate::initialization::{calc_initialization, InitializationType};
use crate::regularization::Regularization;
pub struct NN {
weights: Vec<Array2<f32>>, bias: Vec<Array2<f32>>, shape: Vec<usize>,
pub learning_rate: f32,
hidden_type: ActivationType,
output_type: ActivationType,
regularization: Regularization,
use_softmax_crossentropy: bool, }
impl NN {
pub fn new(network_shape: &[usize]) -> NN {
let mut weights = vec![];
let mut bias = vec![];
let mut values = vec![];
let layers = network_shape.len();
assert!(
layers >= 2,
"Network must have at least 2 layers: input and output"
);
for l1 in 0..layers {
let this_size = network_shape[l1];
values.push(Array::from_shape_fn([1, this_size], |_| 0.));
if l1 < layers - 1 {
let next_size = network_shape[l1 + 1];
bias.push(Array::from_shape_fn([1, next_size], |_| 0.));
weights.push(Array::from_shape_fn([this_size, next_size], |_| 0.));
}
}
let s = Self {
shape: Vec::from(network_shape),
weights,
bias,
learning_rate: 0.01,
hidden_type: ActivationType::Sigmoid,
output_type: ActivationType::Linear,
regularization: Regularization::None,
use_softmax_crossentropy: false,
};
s.with_initialization(InitializationType::Random)
}
pub fn with_learning_rate(mut self, rate: f32) -> NN {
self.learning_rate = rate;
self
}
pub fn with_hidden_type(mut self, types: ActivationType) -> Self {
self.hidden_type = types;
self
}
pub fn with_output_type(mut self, types: ActivationType) -> Self {
self.output_type = types;
self
}
pub fn with_initialization(mut self, typ: InitializationType) -> Self {
self.reset_weights(typ);
self
}
pub fn with_regularization(mut self, reg: Regularization) -> Self {
self.regularization = reg;
self
}
pub fn with_softmax_and_crossentropy(mut self) -> Self {
self.use_softmax_crossentropy = true;
self
}
pub fn reset_weights(&mut self, typ: InitializationType) {
let layers = self.shape.len();
for l in 0..layers - 1 {
let this_size = self.shape[l];
self.bias[l].mapv_inplace(|_| calc_initialization(typ, this_size));
self.weights[l].mapv_inplace(|_| calc_initialization(typ, this_size));
}
}
pub fn fit_one(&mut self, input: &[f32], targets: &[f32]) {
self.fit_batch(&[&input.to_vec()], &[&targets.to_vec()]);
}
pub fn fit(&mut self, inputs: &[&Vec<f32>], targets: &[&Vec<f32>], batch_size: usize) {
inputs
.chunks(batch_size)
.zip(targets.chunks(batch_size))
.for_each(|(inps, outs)| self.fit_batch(inps, outs));
}
pub fn fit_batch(&mut self, inputs: &[&Vec<f32>], targets: &[&Vec<f32>]) {
assert_eq!(
&targets[0].len(),
self.shape.last().unwrap(),
"Target size does not match network output size"
);
let inputs_matrix = self.to_matrix(inputs);
let targets_matrix = self.to_matrix(targets);
let values = self.internal_forward(&inputs_matrix);
let outputs = values.last().expect("There should be outputs").clone();
let loss = self.output_loss(&outputs, &targets_matrix);
let (mut weights, biases) = self.backwards(values, loss);
self.regularize(&mut weights);
self.apply_gradients(&weights, &biases);
}
fn to_matrix(&self, vec: &[&Vec<f32>]) -> Array2<f32> {
Array2::from_shape_vec(
(vec.len(), vec[0].len()),
vec.iter().flat_map(|x| x.to_owned()).copied().collect(),
)
.expect("shape not allowed by size of vec")
}
pub fn forward(&self, input: &[f32]) -> Vec<f32> {
let inputs = self.to_matrix(&[&input.to_vec()]);
let values = self.internal_forward(&inputs);
values
.last()
.expect("There should be outputs")
.clone()
.into_raw_vec()
}
pub fn forward_error(&self, input: &[f32], target: &[f32]) -> f32 {
self.calc_error(&self.forward(input), target)
}
pub fn forward_errors(&self, inputs: &[&Vec<f32>], targets: &[&Vec<f32>]) -> f32 {
let inputs = self.to_matrix(inputs);
let targets = self.to_matrix(targets);
self.internal_forward_errors(&inputs, &targets)
}
fn internal_forward_errors(&self, inputs: &Array2<f32>, targets: &Array2<f32>) -> f32 {
let count = inputs.shape()[0];
let vals = self.internal_forward(inputs);
let outs = vals.last().expect("There should be outputs");
let errs = self.internal_calc_errors(outs, targets);
errs.iter().sum::<f32>() / count as f32
}
pub fn calc_error(&self, outputs: &[f32], target: &[f32]) -> f32 {
let outputs =
Array2::from_shape_vec((1, outputs.len()), outputs.to_vec()).expect("Shape is correct");
let target =
Array2::from_shape_vec((1, target.len()), target.to_vec()).expect("Shape is correct");
self.internal_calc_errors(&outputs, &target)[0]
}
fn internal_calc_errors(&self, outputs: &Array2<f32>, target: &Array2<f32>) -> Vec<f32> {
if self.use_softmax_crossentropy {
let really_small = 0.0000001; let mut err = outputs.mapv(|a| (a + really_small).ln());
err *= -1.;
err *= target;
let sums = err.sum_axis(Axis(1));
sums.to_vec()
} else {
let mut diff = target - outputs;
diff.mapv_inplace(|x| 0.5 * x.powi(2));
let sums = diff.sum_axis(Axis(1));
sums.to_vec()
}
}
fn output_loss(&self, outputs: &Array2<f32>, target: &Array2<f32>) -> Array2<f32> {
outputs - target
}
fn internal_forward(&self, input: &Array2<f32>) -> Vec<Array2<f32>> {
assert_eq!(
input.shape()[1],
self.shape[0],
"Input size does not equal first layer size"
); let example_count = input.shape()[0];
let mut values = self
.shape
.iter()
.map(|size| Array::zeros([example_count, *size]))
.collect::<Vec<_>>();
values[0] = input.clone();
let layers = self.shape.len();
for l in 0..layers - 1 {
let vals = &values[l];
let weights = &self.weights[l];
let is_last_layer = l == layers - 2;
let bias = &self.bias[l];
let ltype = if is_last_layer {
if self.use_softmax_crossentropy {
ActivationType::Linear } else {
self.output_type
}
} else {
self.hidden_type
};
let mut sum = vals.dot(weights) + bias;
sum.mapv_inplace(|a| activate(a, ltype));
if is_last_layer && self.use_softmax_crossentropy {
sum.mapv_inplace(f32::exp); let sums = sum.sum_axis(Axis(1)); for (ri, mut r) in sum.rows_mut().into_iter().enumerate() {
r.mapv_inplace(|a| a / sums[ri]);
}
}
values[l + 1] = sum;
}
values
}
fn backwards(
&self,
values: Vec<Array2<f32>>,
output_gradient: Array2<f32>,
) -> (Vec<Array2<f32>>, Vec<Array2<f32>>) {
let layers = self.shape.len();
let mut weight_gradients = vec![];
let mut bias_gradients = vec![];
let example_count = output_gradient.shape()[0];
let mut next_layer_error_deriv = output_gradient; for l in (0..layers - 1).rev() {
let next_values = &values[l + 1]; let this_values = &values[l]; let this_weights = &self.weights[l]; let is_last_layer = l == layers - 2;
let ltype = if is_last_layer {
if self.use_softmax_crossentropy {
ActivationType::Linear
} else {
self.output_type
}
} else {
self.hidden_type
};
let da_dz = next_values.map(|&a| activate_der(a, ltype)); let de_dz = &next_layer_error_deriv * &da_dz; let ones: Array2<f32> = Array2::ones((1, example_count));
let error_grad_bias = ones.dot(&de_dz); let error_grad_weights = this_values.t().dot(&de_dz); next_layer_error_deriv = de_dz.dot(&this_weights.t()); weight_gradients.insert(0, error_grad_weights);
bias_gradients.insert(0, error_grad_bias.to_owned());
}
for layer in &mut weight_gradients {
layer.mapv_inplace(|a| a / example_count as f32);
}
for layer in &mut bias_gradients {
layer.mapv_inplace(|a| a / example_count as f32);
}
(weight_gradients, bias_gradients)
}
fn regularize(&self, weight_gradients: &mut [Array2<f32>]) {
match self.regularization {
Regularization::None => {}
Regularization::L1(lambda) => {
for (wlayer, gradlayer) in self.weights.iter().zip(weight_gradients.iter_mut()) {
*gradlayer += &(wlayer.mapv(f32::signum) * lambda);
}
}
Regularization::L2(lambda) => {
for (wlayer, gradlayer) in self.weights.iter().zip(weight_gradients.iter_mut()) {
*gradlayer += &(wlayer * lambda);
}
}
Regularization::L1L2(l1lambda, l2lambda) => {
for (wlayer, gradlayer) in self.weights.iter().zip(weight_gradients.iter_mut()) {
let l1: Array2<f32> = wlayer.mapv(f32::signum) * l1lambda;
let l2: Array2<f32> = wlayer * l2lambda;
*gradlayer += &(l1 + l2);
}
}
}
}
fn apply_gradients(
&mut self,
weight_gradients: &[Array2<f32>],
bias_gradients: &[Array2<f32>],
) {
let layers = self.shape.len();
for l in 0..layers - 1 {
self.bias[l] = &self.bias[l] - &bias_gradients[l] * self.learning_rate;
self.weights[l] = &self.weights[l] - &weight_gradients[l] * self.learning_rate;
}
}
pub fn save<P: AsRef<Path>>(&self, path: P) {
let mut vec = vec![];
vec.push(format!("learning_rate={}", self.learning_rate));
vec.push(format!("hidden_type={}", self.hidden_type));
vec.push(format!("output_type={}", self.output_type));
vec.push(format!("regularization={}", self.regularization));
vec.push(format!(
"softmax_crossentropy={}",
self.use_softmax_crossentropy
));
vec.push(format!(
"shape={}",
self.shape
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(",")
));
let layers = self.shape.len();
for l in 0..layers - 1 {
let bias = &self.bias[l]
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(";");
vec.push(format!("bias={bias}"));
let weights = &self.weights[l]
.rows()
.into_iter()
.map(|x| {
x.iter()
.map(ToString::to_string)
.collect::<Vec<String>>()
.join(",")
})
.collect::<Vec<_>>()
.join(";");
vec.push(format!("weight={weights}"));
let result = std::fs::write(path.as_ref(), vec.join("\n"));
if let Err(err) = result {
println!(
"Could not write file {:?}: {}",
path.as_ref().as_os_str(),
err
);
}
}
}
pub fn load<P: AsRef<Path>>(path: P) -> Self {
let data: Vec<Vec<String>> = std::fs::read_to_string(path)
.expect("Could not load from file")
.split('\n')
.map(|x| {
x.split('=')
.map(std::string::ToString::to_string)
.collect::<Vec<String>>()
})
.collect();
let mut lr = 0.01f32;
let mut softmax_crossentropy = false;
let mut ht = ActivationType::Sigmoid;
let mut ot = ActivationType::Linear;
let mut reg = Regularization::None;
let mut weights: Vec<Array<f32, Ix2>> = vec![];
let mut biases: Vec<Array<f32, Ix2>> = vec![];
let mut network_shape = vec![];
for line in data {
if line[0] == "learning_rate" {
lr = line[1].parse::<f32>().unwrap_or(0.01);
} else if line[0] == "hidden_type" {
ht = ActivationType::from_str(&line[1]).unwrap_or(ActivationType::Sigmoid);
} else if line[0] == "output_type" {
ot = ActivationType::from_str(&line[1]).unwrap_or(ActivationType::Linear);
} else if line[0] == "regularization" {
reg = Regularization::from_str(&line[1]);
} else if line[0] == "softmax_crossentropy" {
softmax_crossentropy = line[1].parse::<bool>().unwrap_or_default();
} else if line[0] == "weight" {
let ww: Vec<Vec<f32>> = line[1]
.split(';')
.map(|x| {
x.split(',')
.filter_map(|f| f.parse::<f32>().ok())
.collect::<Vec<f32>>()
})
.collect();
let r = ww.len();
let c = ww[0].len();
let ww = ww.iter().flatten().copied().collect::<Vec<f32>>();
let ww = Array2::from_shape_vec([r, c], ww).expect("Shape is wrong for vec");
weights.push(ww);
} else if line[0] == "bias" {
let bb = line[1]
.split(';')
.map(|f| f.parse::<f32>().unwrap_or_default())
.collect::<Vec<f32>>();
let bb = bb;
let bb = Array2::from_shape_vec([1, bb.len()], bb).expect("Shape is wrong for vec");
biases.push(bb);
} else if line[0] == "shape" {
network_shape = line[1]
.split(',')
.map(|f| f.parse::<usize>().unwrap_or_default())
.collect::<Vec<usize>>();
}
}
let mut weight_shape = vec![];
for l in &weights {
weight_shape.push(l.shape()[0]);
}
weight_shape.push(weights.last().expect("There should be weights").shape()[1]);
assert_eq!(
network_shape, weight_shape,
"Weight shape does not equal to shape"
);
let mut s = Self::new(&network_shape)
.with_hidden_type(ht)
.with_output_type(ot)
.with_regularization(reg)
.with_learning_rate(lr);
s.use_softmax_crossentropy = softmax_crossentropy;
s.weights = weights;
s.bias = biases;
s
}
pub fn get_weights(&self) -> Vec<f32> {
let mut weights = vec![];
for l in 0..self.weights.len() {
for i in &self.weights[l] {
weights.push(*i);
}
for i in &self.bias[l] {
weights.push(*i);
}
}
weights
}
pub fn set_weights(&mut self, weights: &[f32]) {
let mut counter = 0;
for l in 0..self.weights.len() {
for i in self.weights[l].iter_mut() {
*i = weights[counter];
counter += 1;
}
for i in self.bias[l].iter_mut() {
*i = weights[counter];
counter += 1;
}
}
}
pub fn get_shape(&self) -> Vec<usize> {
self.shape.clone()
}
}
impl Display for NN {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut str = String::new();
str.push_str(
self.shape
.iter()
.map(std::string::ToString::to_string)
.collect::<Vec<String>>()
.join(", ")
.as_str(),
);
str.push_str("\nweights: \n");
let wei = &self.weights;
for l in wei {
str.push_str(l.to_string().as_str());
str.push('\n');
}
str.push('\n');
str.push_str("\nbiases: \n");
let wei = &self.bias;
for l in wei {
str.push_str(l.to_string().as_str());
str.push('\n');
}
str.push('\n');
write!(f, "{str}")
}
}
pub fn max_index_equal(target: &[f32], predicted: &[f32]) -> bool {
assert_eq!(
target.len(),
predicted.len(),
"Target and predicted should have same length"
);
let pred = max_index(predicted);
let tar = max_index(target);
pred == tar
}
pub fn max_index(vec: &[f32]) -> usize {
vec.iter()
.enumerate()
.max_by(|a, b| a.1.total_cmp(b.1))
.expect("max_index expects a vec with non zero size")
.0
}
pub struct TargetPredicted {
pub target: f32,
pub predicted: f32,
}
pub type CustomMetric = fn(Vec<Vec<TargetPredicted>>) -> String;
pub enum ReportMetric {
None,
CorrectClassification,
RSquared,
Custom(CustomMetric),
}
pub fn run_and_report(
set: &Dataset,
net: &mut NN,
epochs: usize,
batch_size: usize,
report_epoch: usize,
metric: ReportMetric,
) {
let start = Instant::now();
let acc = match metric {
ReportMetric::None => "",
ReportMetric::CorrectClassification => " train_acc test_acc",
ReportMetric::RSquared => " train_R² test R²",
ReportMetric::Custom(_) => " train_acc test_acc",
};
println!("epoch train_error test_error{acc} duration(s)");
for e in 1..=epochs {
let (inp, tar) = set.get_data();
net.fit(&inp, &tar, batch_size);
if report_epoch > 0 && e % report_epoch == 0 {
let train_err = net.forward_errors(&inp, &tar);
let (inp_test, tar_test) = set.get_test_data();
let test_err = net.forward_errors(&inp_test, &tar_test);
let mut acc = "".to_string();
match metric {
ReportMetric::None => {}
ReportMetric::CorrectClassification => {
let mut train_count = 0;
for (inp, tar) in inp.iter().zip(tar) {
let pred = net.forward(inp);
if max_index_equal(tar, &pred) {
train_count += 1;
}
}
let mut test_count = 0;
for (inp, tar) in inp_test.iter().zip(tar_test) {
let pred = net.forward(inp);
if max_index_equal(tar, &pred) {
test_count += 1;
}
}
let train_acc = train_count as f32 / inp.len() as f32 * 100.;
let test_acc = test_count as f32 / inp_test.len() as f32 * 100.;
acc = format!(" {train_acc:.2}% {test_acc:.2}%");
}
ReportMetric::RSquared => {
let data = [(inp, tar), (inp_test, tar_test)];
let mut r2 = vec![];
for (inp, tar) in data {
let pred: Vec<Vec<f32>> = inp.iter().map(|inp| net.forward(inp)).collect();
let mut r2s = vec![];
for i in 0..tar[0].len() {
let tar = tar.iter().map(|x| x[i]).collect::<Vec<_>>();
let pred = pred.iter().map(|x| x[i]).collect::<Vec<_>>();
let avg: f32 = tar.iter().sum::<f32>() / tar.len() as f32;
let sst = tar.iter().map(|x| (x - avg).powi(2)).sum::<f32>();
let ssr = tar
.into_iter()
.zip(pred)
.map(|(tar, pred)| (tar - pred).powi(2))
.sum::<f32>();
let r2 = 1. - ssr / sst;
r2s.push(r2);
}
r2.push(r2s.iter().sum::<f32>() / r2s.len() as f32);
}
acc = format!(" {} {}", r2[0], r2[1]);
}
ReportMetric::Custom(fun) => {
let mut trains = vec![];
for (inp, tar) in inp.iter().zip(tar) {
let pred = net.forward(inp);
trains.push(
tar.iter()
.zip(pred)
.map(|a| TargetPredicted {
target: *a.0,
predicted: a.1,
})
.collect::<Vec<_>>(),
);
}
let mut tests = vec![];
for (inp, tar) in inp_test.iter().zip(tar_test) {
let pred = net.forward(inp);
tests.push(
tar.iter()
.zip(pred)
.map(|a| TargetPredicted {
target: *a.0,
predicted: a.1,
})
.collect::<Vec<_>>(),
);
}
acc = format!(" {} {}", fun(trains), fun(tests));
}
}
println!(
"{e} {train_err} {test_err}{acc} {:.1}",
start.elapsed().as_secs_f32()
);
}
}
}
#[cfg(test)]
#[path = "tests.rs"]
mod tests;