-
Notifications
You must be signed in to change notification settings - Fork 58
/
Model.cs
2106 lines (1819 loc) · 92.1 KB
/
Model.cs
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
// Keras-Sharp: C# port of the Keras library
// https://github.com/cesarsouza/keras-sharp
//
// Based under the Keras library for Python. See LICENSE text for more details.
//
// The MIT License(MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
namespace KerasSharp.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KerasSharp.Engine;
using System.Diagnostics;
using KerasSharp.Metrics;
using KerasSharp.Engine.Topology;
using KerasSharp.Losses;
using static KerasSharp.Backends.Current;
using static KerasSharp.Python;
using Accord.Math;
using System.Collections;
public static class ExtensionMethods
{
public static IEnumerable<T> Concatenate<T>(this IEnumerable<T>[] lists)
{
return lists.SelectMany(x => x);
}
}
public class Function
{
public List<Tensor> Call(object ins_batch)
{
throw new NotImplementedException();
}
internal List<Tensor> Call(List<Tensor> ins)
{
throw new NotImplementedException();
}
}
/// <summary>
/// The Model class adds training & evaluation routines to a <see cref="Container"/>.
/// </summary>
///
public partial class Model : Container
{
public bool Trainable { get; set; }
internal Sequential callback_model;
public IOptimizer optimizer;
public Dictionary<string, string> sample_weight_mode;
public Dictionary<string, ILoss> loss;
public Dictionary<string, double> loss_weights;
public Tensor total_loss;
public List<Tensor> sample_weights;
protected List<ILoss> loss_functions;
protected List<Tensor> _feed_outputs;
protected List<string> _feed_output_names;
protected List<int?[]> _feed_output_shapes;
protected List<object> _feed_loss_fns;
public List<Tensor> targets;
protected List<Tensor> _feed_targets;
public IMetric metrics;
public List<string> metrics_names;
public List<Tensor> metrics_tensors;
protected List<Tensor> _feed_sample_weights;
protected List<Tensor> _collected_trainable_weights;
protected Function train_function;
protected Function test_function;
protected Function predict_function;
protected bool stop_training;
protected History history;
public List<object> _feed_sample_weight_modes;
public Model()
{
}
public Model(List<Tensor> inputs, List<Tensor> outputs, string name = null)
: base(inputs, outputs, name)
{
}
/// <summary>
/// Configures the model for training.
/// </summary>
///
/// <param name="optimizer">The optimization algorithm.</param>
/// <param name="loss">The objective function (to be minimized). model has multiple outputs, you can use a different loss
/// on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model
/// will then be the sum of all individual losses.</param>
/// <param name="metrics">The list of metrics to be evaluated by the model during training and testing. Typically you
/// will use `metrics =['accuracy']`. To specify different metrics for different outputs of a multi - output model,
/// you could also pass a dictionary, such as `metrics ={ 'output_a': 'accuracy'}`.</param>
/// <param name="loss_weights">The optional list or dictionary specifying scalar coefficients (Python floats) to weight
/// the loss contributions of different model outputs. The loss value that will be minimized by the model will then be
/// the *weighted sum* of all individual losses, weighted by the `loss_weights` coefficients. If a list, it is expected
/// to have a 1:1 mapping to the model's outputs. If a tensor, it is expected to map output names(strings) to scalar
/// coefficients.</param>
/// <param name="sample_weight_mode">If you need to do timestep - wise sample weighting(2D weights), set this to `"temporal"`.
/// `null` defaults to sample - wise weights(1D). If the model has multiple outputs, you can use a different `sample_weight_mode`
/// on each output by passing a dictionary or a list of modes.</param>
///
public void Compile(IOptimizer optimizer, ILoss loss, IMetric metrics = null)
{
Compile(optimizer, loss.to_dict(), metrics);
}
public void Compile(IOptimizer optimizer, List<ILoss> loss, IMetric metrics = null)
{
Compile(optimizer, loss.to_dict(), metrics);
}
public void Compile(string optimizer, string loss, string[] metrics = null)
{
// TODO: Translate strings into actual classes and instantiate them
throw new NotImplementedException();
}
public void Compile(IOptimizer optimizer, string loss, string[] metrics = null)
{
// TODO: Translate strings into actual classes and instantiate them
throw new NotImplementedException();
}
public void Compile(string optimizer, string loss, object[] metrics)
{
// TODO: Translate strings into actual classes and instantiate them
throw new NotImplementedException();
}
/// <summary>
/// Configures the model for training.
/// </summary>
///
/// <param name="optimizer">The optimization algorithm.</param>
/// <param name="loss">The objective function (to be minimized). model has multiple outputs, you can use a different loss
/// on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model
/// will then be the sum of all individual losses.</param>
/// <param name="metrics">The list of metrics to be evaluated by the model during training and testing. Typically you
/// will use `metrics =['accuracy']`. To specify different metrics for different outputs of a multi - output model,
/// you could also pass a dictionary, such as `metrics ={ 'output_a': 'accuracy'}`.</param>
/// <param name="loss_weights">The optional list or dictionary specifying scalar coefficients (Python floats) to weight
/// the loss contributions of different model outputs. The loss value that will be minimized by the model will then be
/// the *weighted sum* of all individual losses, weighted by the `loss_weights` coefficients. If a list, it is expected
/// to have a 1:1 mapping to the model's outputs. If a tensor, it is expected to map output names(strings) to scalar
/// coefficients.</param>
/// <param name="sample_weight_mode">If you need to do timestep - wise sample weighting(2D weights), set this to `"temporal"`.
/// `null` defaults to sample - wise weights(1D). If the model has multiple outputs, you can use a different `sample_weight_mode`
/// on each output by passing a dictionary or a list of modes.</param>
///
public virtual void Compile(IOptimizer optimizer, Dictionary<string, ILoss> loss, IMetric metrics = null,
Dictionary<string, double> loss_weights = null, Dictionary<string, string> sample_weight_mode = null)
{
// https://github.com/fchollet/keras/blob/f65a56fb65062c8d14d215c9f4b1015b97cc5bf3/keras/engine/training.py#L681
if (loss == null)
loss = new Dictionary<string, ILoss>();
this.optimizer = optimizer;
this.sample_weight_mode = sample_weight_mode;
this.loss = loss;
this.loss_weights = loss_weights;
// Prepare loss functions.
var loss_functions = new List<ILoss>();
if (loss.is_dict())
{
foreach (string name in loss.Keys)
{
if (!this.output_names.Contains(name))
throw new Exception($"Unknown entry in loss dictionary: {name}. Only expected the following keys: {this.output_names}");
}
foreach (string name in this.output_names)
{
if (!loss.ContainsKey(name))
{
Trace.TraceWarning($"Output {name} missing from loss dictionary. We assume this was done on purpose, and we will not be expecting any data to be passed to {name} during training.");
loss_functions.Add(loss[name]);
}
}
}
else if (loss.is_list())
{
List<ILoss> list = loss.to_list();
if (list.Count != this.outputs.Count)
throw new Exception($"When passing a list as loss, it should have one entry per model outputs. The model has " +
$"{this.outputs.Count} outputs, but you passed loss={loss}");
loss_functions = list;
}
else
{
ILoss loss_function = loss.to_single();
loss_functions = this.outputs.Select(x => loss_function).ToList();
}
this.loss_functions = loss_functions;
List<ILoss> weighted_losses = loss_functions.Select(fn => _weighted_masked_objective(fn)).ToList();
var skip_indices = new List<int>();
this._feed_outputs = new List<Tensor>();
this._feed_output_names = new List<string>();
this._feed_output_shapes = new List<int?[]>();
this._feed_loss_fns = new List<object>();
for (int i = 0; i < weighted_losses.Count; i++)
{
if (weighted_losses[i] == null)
{
skip_indices.Add(i);
}
else
{
this._feed_outputs.Add(this.outputs[i]);
this._feed_output_names.Add(this.output_names[i]);
this._feed_output_shapes.Add(this.internal_output_shapes[i]);
this._feed_loss_fns.Add(this.loss_functions[i]);
}
}
// Prepare output masks.
// https://github.com/fchollet/keras/blob/f65a56fb65062c8d14d215c9f4b1015b97cc5bf3/keras/engine/training.py#L774
var masks = this.compute_mask(this.inputs, mask: null);
if (masks == null)
masks = this.output.Select(x => (Tensor)null).ToList();
// Prepare loss weights.
// https://github.com/fchollet/keras/blob/f65a56fb65062c8d14d215c9f4b1015b97cc5bf3/keras/engine/training.py#L781
List<double> loss_weights_list;
if (loss_weights == null)
{
loss_weights_list = this.outputs.Select(x => 1.0).ToList();
}
else if (loss_weights.is_dict())
{
foreach (string name in loss_weights.Keys)
{
if (!this.output_names.Contains(name))
throw new InvalidOperationException($"Unknown entry in loss_weights dictionary: '{name}'. Only expected the following keys: {str(this.output_names)}.");
}
loss_weights_list = new List<double>();
foreach (string name in this.output_names)
loss_weights_list.Add(loss_weights.get(name, 1.0));
}
else if (loss_weights.is_list())
{
List<double> lw = loss_weights.to_list();
if (lw.Count != this.outputs.Count)
throw new InvalidOperationException($"When passing a list as loss_weights, it should have one entry per model outputs. The model has {str(this.outputs.Count)} outputs, but you passed loss_weights='{str(loss_weights)}'.");
loss_weights_list = lw;
}
else
{
throw new InvalidOperationException($"Could not interpret loss_weights argument: {str(loss_weights)} - expected a list of dicts.");
}
// Prepare sample weights.
// https://github.com/fchollet/keras/blob/f65a56fb65062c8d14d215c9f4b1015b97cc5bf3/keras/engine/training.py#L807
var sample_weights = new List<Tensor>();
var sample_weight_modes = new List<string>();
if (sample_weight_mode.is_dict())
{
foreach (string name in sample_weight_mode.Keys)
{
if (!this.output_names.Contains(name))
{
if (!this.output_names.Contains(name))
throw new InvalidOperationException($"Unknown entry in sample_weight_mode dictionary: {name}. Only expected the following keys: {str(this.output_names)}.");
}
}
for (int i = 0; i < this.output_names.Count; i++)
{
string name = this.output_names[i];
Tensor weight;
if (skip_indices.Contains(i))
{
weight = null;
sample_weight_modes.Add(null);
}
else
{
if (!sample_weight_mode.Keys.Contains(name))
throw new InvalidOperationException($"Output '{name}' missing from sample_weight_modes dictionary.");
if (sample_weight_mode[name] == "temporal")
{
weight = K.placeholder(ndim: 2, name: name + "_sample_weights");
sample_weight_modes.Add("temporal");
}
else
{
weight = K.placeholder(ndim: 1, name: name + "_sample_weights");
sample_weight_modes.Add(null);
}
}
sample_weights.Add(weight);
}
}
else if (sample_weight_mode.is_list())
{
var swm = sample_weight_mode.to_list();
if (swm.Count != this.outputs.Count)
throw new InvalidOperationException($"When passing a list as sample_weight_mode, it should have one entry per model outputs. The model has {str(this.outputs.Count)} outputs, but you passed sample_weight_mode={str(sample_weight_mode)}");
for (int i = 0; i < this.output_names.Count; i++)
{
Tensor weight;
if (skip_indices.Contains(i))
{
weight = null;
swm.Add(null);
}
else
{
var mode = swm[i];
name = this.output_names[i];
if (mode == "temporal")
{
weight = K.placeholder(ndim: 2, name: name + "_sample_weights");
sample_weight_modes.Add("temporal");
}
else
{
weight = K.placeholder(ndim: 1, name: name + "_sample_weights");
sample_weight_modes.Add(null);
}
}
sample_weights.Add(weight);
}
}
else
{
for (int i = 0; i < this.output_names.Count; i++)
{
var swm = sample_weight_mode.to_single();
string name = this.output_names[i];
if (skip_indices.Contains(i))
{
sample_weight_modes.Add(null);
sample_weights.Add(null);
}
else
{
if (swm == "temporal")
{
sample_weights.Add(K.placeholder(ndim: 2, name: name + "_sample_weights"));
sample_weight_modes.Add("temporal");
}
else
{
sample_weights.Add(K.placeholder(ndim: 1, name: name + "_sample_weights"));
sample_weight_modes.Add(null);
}
}
}
}
// Prepare targets of model.
// https://github.com/fchollet/keras/blob/f65a56fb65062c8d14d215c9f4b1015b97cc5bf3/keras/engine/training.py#L882
this.targets = new List<Tensor>();
this._feed_targets = new List<Tensor>();
for (int i = 0; i < this.output_names.Count; i++)
{
string name = this.output_names[i];
if (skip_indices.Contains(i))
{
this.targets.Add(null);
}
else
{
int?[] shape = this.internal_output_shapes[i];
Tensor target = K.placeholder(ndim: shape.Length, name: name + "_target", sparse: K.is_sparse(this.outputs[i]), dtype: K.dtype(this.outputs[i]));
this.targets.Add(target);
this._feed_targets.Add(target);
}
}
// Prepare metrics.
this.metrics = metrics;
this.metrics_names = new List<string>() { "loss" };
this.metrics_tensors = new List<Tensor>();
// Compute total loss.
// https://github.com/fchollet/keras/blob/f65a56fb65062c8d14d215c9f4b1015b97cc5bf3/keras/engine/training.py#L903
Tensor total_loss = null;
using (K.name_scope("loss"))
{
for (int i = 0; i < this.outputs.Count; i++)
{
if (skip_indices.Contains(i))
continue;
Tensor y_true = this.targets[i];
Tensor y_pred = this.outputs[i];
ILoss weighted_loss = weighted_losses[i];
Tensor sample_weight = sample_weights[i];
Tensor mask = masks[i];
double loss_weight = loss_weights_list[i];
Tensor output_loss;
using (K.name_scope(this.output_names[i] + "_loss"))
output_loss = weighted_loss.Call(y_true, y_pred, sample_weight, mask);
if (this.outputs.Count > 1)
{
this.metrics_tensors.Add(output_loss);
this.metrics_names.Add(this.output_names[i] + "_loss");
}
if (total_loss == null)
total_loss = K.mul(loss_weight, output_loss);
else
total_loss = K.add(total_loss, K.mul(loss_weight, output_loss));
}
if (total_loss == null)
{
if (this.losses.Count == 0)
throw new Exception($"The model cannot be compiled because it has no loss to optimize.");
else total_loss = K.constant(0.0);
}
// Add regularization penalties
// and other layer-specific losses.
foreach (Tensor loss_tensor in this.losses)
{
total_loss = K.add(total_loss, loss_tensor);
}
}
// List of same size as output_names.
// contains tuples (metrics for output, names of metrics).
List<List<IMetric>> nested_metrics = _collect_metrics(metrics, this.output_names);
void append_metric(int layer_num, string metric_name, Tensor metric_tensor)
{
// """Helper function used in loop below."""
if (output_names.Count > 1)
{
metric_name = this.output_layers[layer_num].name + "_" + metric_name;
this.metrics_names.Add(metric_name);
this.metrics_tensors.Add(metric_tensor);
}
}
List<Tensor> metric_result = null;
for (int i = 0; i < this.outputs.Count; i++)
{
if (skip_indices.Contains(i))
continue;
Tensor y_true = this.targets[i];
Tensor y_pred = this.outputs[i];
List<IMetric> output_metrics = nested_metrics[i];
foreach (IMetric metric in output_metrics)
{
//if (metric is IAccuracy)
//{
// // custom handling of accuracy
// // (because of class mode duality)
// int?[] output_shape = this.internal_output_shapes[i];
// object acc_fn = null;
// if (output_shape.Get(-1) == 1 || this.loss_functions[i] is BinaryCrossEntropy)
// {
// // case: binary accuracy
// acc_fn = new BinaryAccuracy();
// }
// else if (this.loss_functions[i] is SparseCategoricalCrossEntropy)
// {
// // case: categorical accuracy with sparse targets
// acc_fn = new SparseCategoricalAccuracy();
// }
// else
// {
// acc_fn = new CategoricalAccuracy();
// }
// var masked_fn = _masked_objective(acc_fn);
// append_metric(i, "acc", masked_fn(y_true, y_pred, mask = masks[i]));
//}
//else
//{
IMetric metric_fn = metric;
IMetric masked_metric_fn = _masked_objective(metric_fn);
metric_result = masked_metric_fn.Call(y_true, y_pred, mask: masks[i]);
//}
}
}
for (int i = 0; i < metric_result.Count; i++)
{
string name = metric_result[i].name;
Tensor tensor = metric_result[i];
append_metric(i, name, tensor);
}
// Prepare gradient updates and state updates.
this.total_loss = total_loss;
this.sample_weights = sample_weights;
this._feed_sample_weights = new List<Tensor>();
for (int i = 0; i < this.sample_weights.Count; i++)
{
if (!skip_indices.Contains(i))
this._feed_sample_weights.Add(sample_weights[i]);
}
// Functions for train, test and predict will
// be compiled lazily when required.
// This saves time when the user != using all functions.
//this._function_kwargs = kwargs
this.train_function = null;
this.test_function = null;
this.predict_function = null;
// Collected trainable weights and sort them deterministically.
trainable_weights = this.trainable_weights;
// Sort weights by name.
if (trainable_weights.Count > 0)
{
trainable_weights.OrderBy(keySelector: x => x.name);
this._collected_trainable_weights = trainable_weights;
}
}
/// <summary>
/// Maps metric functions to model outputs.
/// </summary>
///
/// <param name="metrics">A list or dict of metric functions.</param>
/// <param name="output_names">A list of the names (strings) of model outputs.</param>
/// <returns>A list (one entry per model output) of lists of metric functions.</returns>
///
private List<List<IMetric>> _collect_metrics(IMetric metrics, List<string> output_names)
{
// https://github.com/fchollet/keras/blob/f65a56fb65062c8d14d215c9f4b1015b97cc5bf3/keras/engine/training.py#L293
throw new NotImplementedException();
}
private IMetric _masked_objective(IMetric metric_fn)
{
throw new NotImplementedException();
}
/// <summary>
/// Adds support for masking and sample-weighting to an objective function.
/// It transforms an objective function `fn(y_true, y_pred)` into a sample -
/// weighted, cost - masked objective function `fn(y_true, y_pred, weights, mask)`.
/// </summary>
///
/// <param name="fn">The objective function to wrap, with signature `fn(y_true, y_pred)`.</param>
///
/// <returns>A function with signature `fn(y_true, y_pred, weights, mask)`.</returns>
///
private ILoss _weighted_masked_objective(ILoss fn)
{
// https://github.com/fchollet/keras/blob/f65a56fb65062c8d14d215c9f4b1015b97cc5bf3/keras/engine/training.py#L406
if (fn == null)
return null;
Tensor weighted(Tensor y_true, Tensor y_pred, Tensor weights, Tensor mask = null)
{
// score_array has ndim >= 2
Tensor score_array = fn.Call(y_true, y_pred);
if (mask != null)
{
// Cast the mask to floatX to avoid float64 upcasting in theano
mask = K.cast(mask, K.floatx());
// mask should have the same shape as score_array
score_array = score_array * mask;
// the loss per batch should be proportional
// to the number of unmasked samples.
score_array = score_array / K.mean(mask);
}
// reduce score_array to same ndim as weight array
int? ndim = K.ndim(score_array);
int? weight_ndim = K.ndim(weights);
if (ndim != weight_ndim)
score_array = K.mean(score_array, axis: range(weight_ndim, ndim));
// apply sample weighting
if (weights != null)
{
score_array = score_array * weights;
score_array = score_array / K.mean(K.cast(K.not_equal(weights, 0), K.floatx()));
}
return K.mean(score_array);
}
return new CustomLoss(weighted);
}
public void _make_train_function()
{
if (this.train_function == null)
throw new Exception("You must compile your model before using it.");
if (this.train_function == null)
{
var inputs = (Enumerable.Concat(this._feed_inputs, this._feed_targets).Concat(this._feed_sample_weights)).ToList();
if (this.uses_learning_phase && !(K.learning_phase() is int))
inputs.Add((Tensor)K.learning_phase());
List<List<Tensor>> training_updates = this.optimizer.get_updates(this._collected_trainable_weights, this.constraints, this.total_loss);
var updates = Enumerable.Concat(this.updates, training_updates).ToList();
// Gets loss and metrics. Updates weights at each call.
this.train_function = K.function(inputs, ((new[] { this.total_loss }).Concat(this.metrics_tensors)).ToList(),
updates: updates, name: "train_function"); //, **this._function_kwargs)
}
}
public void _make_test_function()
{
if (this.test_function == null)
throw new Exception("You must compile your model before using it.");
if (this.test_function == null)
{
var inputs = this._feed_inputs.Concat(this._feed_targets).Concat(this._feed_sample_weights).ToList();
if (this.uses_learning_phase && !(K.learning_phase() is int))
inputs.Add((Tensor)K.learning_phase());
// Return loss and metrics, no gradient updates.
// Does update the network states.
this.test_function = K.function(inputs, new[] { this.total_loss }.Concat(this.metrics_tensors).ToList(),
updates: this.state_updates, name: "test_function"); //, **this._function_kwargs);
}
}
public void _make_predict_function()
{
if (this.predict_function == null)
this.predict_function = null;
if (this.predict_function == null)
{
if (this.uses_learning_phase && !(K.learning_phase() is int))
{
inputs = this._feed_inputs.Concat(new List<Tensor>() { (Tensor)K.learning_phase() }).ToList();
}
else
{
inputs = this._feed_inputs;
}
// Gets network outputs. Does not update weights.
// Does update the network states.
// kwargs = getattr( "_function_kwargs', { });
this.predict_function = K.function(inputs, this.outputs,
updates: this.state_updates, name: "predict_function"); //, **kwargs);
}
}
public History _fit_loop(Function f, List<Tensor> ins, List<string> out_labels = null,
int batch_size = 32, int epochs = 100, int verbose = 1, CallbackList callbacks = null,
Function val_f = null, List<Tensor> val_ins = null, string shuffle = "true",
List<String> callback_metrics = null, int initial_epoch = 0)
{
// """Abstract fit function for `f(ins)`.
// Assume that f returns a list, labeled by out_labels.
// // Arguments
// f: Keras function returning a list of tensors
// ins: list of tensors to be fed to `f`
// out_labels: list of strings, display names of
// the outputs of `f`
// batch_size: integer batch size
// epochs: number of times to iterate over the data
// verbose: verbosity mode, 0, 1 or 2
// callbacks: list of callbacks to be called during training
// val_f: Keras function to call for validation
// val_ins: list of tensors to be fed to `val_f`
// shuffle: whether to shuffle the data at the beginning of each epoch
// callback_metrics: list of strings, the display names of the metrics
// passed to the callbacks. They should be the
// concatenation of list the display names of the outputs of
// `f` and the list of display names of the outputs of `f_val`.
// initial_epoch: epoch at which to start training
// (useful for resuming a previous training run)
// // Returns
// `History` object.
// """
bool do_validation = false;
if (val_f != null && val_ins != null)
do_validation = true;
if (verbose > 0)
Trace.Write("Train on {ins[0].shape[0]} samples, validate on val_ins[0].shape[0] samples");
int num_train_samples;
if (ins != null && ((Tensor)ins[0]).shape != null)
{
num_train_samples = ((Tensor)ins[0]).shape[0].Value;
}
else
{
// May happen if we are running `fit` without Numpy input data,
// i.e. if all inputs to the models are data tensors
// instead of placeholders.
// In that case we will run `fit` over a single batch.
num_train_samples = batch_size;
verbose = 2;
}
int[] index_array = Vector.Range(num_train_samples);
this.history = new History();
callbacks.Add(new BaseLogger());
callbacks.Add(this.history);
if (verbose > 0)
callbacks.Add(new ProgbarLogger());
//callbacks = cbks.CallbackList(callbacks);
if (out_labels == null)
out_labels = new List<string>();
// it's possible to callback a different model than this
// (used by Sequential models)
Model callback_model;
if (this.callback_model != null && this.callback_model != null)
callback_model = this.callback_model;
else
callback_model = this;
//callbacks.set_model(callback_model);
//callbacks.set_params({
// 'batch_size': batch_size,
// 'epochs': epochs,
// 'samples': num_train_samples,
// 'verbose': verbose,
// 'do_validation': do_validation,
// 'metrics': callback_metrics or [],
//});
callbacks.on_train_begin();
callback_model.stop_training = false;
foreach (Callback cbk in callbacks)
cbk.validation_data = val_ins;
for (int epoch = initial_epoch; epoch < epochs; epoch++)
{
callbacks.on_epoch_begin(epoch);
if (shuffle == "batch")
index_array = _batch_shuffle(index_array, batch_size);
else if (shuffle == "true")
Vector.Shuffle(index_array);
List<(int, int)> batches = _make_batches(num_train_samples, batch_size);
var epoch_logs = new Dictionary<string, object>();
for (int batch_index = 0; batch_index < batches.Count; batch_index++)
{
var (batch_start, batch_end) = batches[batch_index];
int[] batch_ids = index_array.Get(batch_start, batch_end);
object ins_batch;
try
{
//if (ins[-1] is float)
//{
// // Do not slice the training phase flag.
// ins_batch = _slice_arrays(ins.Get(0, -1), batch_ids) .Concatenate( [ins[-1]];
//}
//else
//{
ins_batch = _slice_arrays(ins, batch_ids);
//}
}
catch
{
throw new Exception($"TypeError while preparing batch. If using HDF5 input data, pass shuffle='batch'.");
}
var batch_logs = new Dictionary<string, object>();
batch_logs["batch"] = batch_index;
batch_logs["size"] = batch_ids.Length;
callbacks.on_batch_begin(batch_index, batch_logs);
List<Tensor> outs = f.Call(ins_batch);
for (int i = 0; i < out_labels.Count; i++)
{
var l = out_labels[i];
var o = outs[i];
batch_logs[l] = o;
}
callbacks.on_batch_end(batch_index, batch_logs);
if (callback_model.stop_training)
break;
if (batch_index == batches.Count - 1) // Last batch.
{
if (do_validation)
{
List<Tensor> val_outs = this._test_loop(val_f, val_ins, batch_size: batch_size, verbose: 0);
// Same labels assumed.
for (int i = 0; i < out_labels.Count; i++)
{
var l = out_labels[i];
var o = val_outs[i];
epoch_logs["val_" + l] = o;
}
}
}
callbacks.on_epoch_end(epoch, epoch_logs);
if (callback_model.stop_training)
break;
}
}
callbacks.on_train_end();
return this.history;
}
private List<Tensor> _slice_arrays(Array ins, params int[] batch_ids)
{
throw new NotImplementedException();
}
private List<(int, int)> _make_batches(int num_train_samples, int batch_size)
{
throw new NotImplementedException();
}
private int[] _batch_shuffle(int[] index_array, int batch_size)
{
throw new NotImplementedException();
}
public Array[] _predict_loop(Function f, List<Tensor> ins, int batch_size = 32, int verbose = 0)
{
// """Abstract method to loop over some data in batches.
// // Arguments
// f: Keras function returning a list of tensors.
// ins: list of tensors to be fed to `f`.
// batch_size: integer batch size.
// verbose: verbosity mode.
// // Returns
// Array of predictions (if the model has a single output)
// or list of arrays of predictions
// (if the model has multiple outputs).
// """
int samples;
if (ins != null && ((Tensor)ins[0]).shape != null)
{
samples = ((Tensor)ins[0]).shape[0].Value;
}
else
{
// May happen if we are running `predict` without Numpy input data,
// i.e. if all inputs to the models are data tensors
// instead of placeholders.
// In that case we will run `predict` over a single batch.
samples = batch_size;
verbose = 2;
}
var outs = new List<Array>();
Progbar progbar = null;
if (verbose == 1)
progbar = new Progbar(target: samples);
List<(int, int)> batches = _make_batches(samples, batch_size);
int[] index_array = Vector.Range(samples);
for (int batch_index = 0; batch_index < batches.Count; batch_index++)
{
var (batch_start, batch_end) = batches[batch_index];
var batch_ids = index_array.Get(batch_start, batch_end);
//if (ins != null && ins[-1] is float)
//{
// // Do not slice the training phase flag.
// ins_batch = _slice_arrays(ins[:-1], batch_ids) + [ins[-1]];
//}
//else
//{
object ins_batch = _slice_arrays(ins, batch_ids);
//}
List<Tensor> batch_outs = f.Call(ins_batch);
if (batch_index == 0)
{
foreach (var batch_out in batch_outs)
{
var shape = new int?[] { samples }.Concatenate(batch_out.shape.Get(1, 0));
//outs.Add(Tensor.Zeros(shape, dtype: KerasSharp.Utils.ToNetType(batch_out.dtype)));
}
}
for (int i = 0; i < batch_outs.Count; i++)
{
var batch_out = batch_outs[i];
//outs[i].Set(batch_start, batch_end, batch_out);
if (verbose == 1)
progbar.update(batch_end);
}
}
return outs.ToArray();
}
/// <summary>
/// Abstract method to loop over some data in batches.
/// </summary>
///
/// <param name="f">Function returning a list of tensors.</param>
/// <param name="ins">The list of tensors to be fed to `f`.</param>
/// <param name="batch_size">The batch size.</param>
/// <param name="verbose">The verbosity mode.</param>
/// <returns>
/// Scalar loss (if the model has a single output and no metrics)
/// or list of scalars (if the model has multiple outputs
/// and/or metrics). The attribute `model.metrics_names` will give you
/// the display labels for the scalar outputs.
/// </returns>
///
public List<Tensor> _test_loop(Function f, List<Tensor> ins, int batch_size = 32, int verbose = 0)
{
int samples;
if (ins != null)
{
samples = ins[0].shape[0].Value;
}
else
{
// May happen if we are running `evaluate` without Numpy input data,
// i.e. if all inputs to the models are data tensors
// instead of placeholders.
// In that case we will run `evaluate` over a single batch.
samples = batch_size;
verbose = 2;