|
1 | | -namespace Tensorflow.Keras.Engine |
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using Tensorflow.Keras.Metrics; |
| 5 | +using static Tensorflow.Binding; |
| 6 | + |
| 7 | +namespace Tensorflow.Keras.Engine |
2 | 8 | { |
3 | 9 | public class MetricsContainer : Container |
4 | 10 | { |
5 | 11 | string[] _user_metrics; |
6 | | - string[] _metrics; |
| 12 | + string[] _metric_names; |
| 13 | + Metric[] _metrics; |
| 14 | + List<Metric> _metrics_in_order; |
7 | 15 |
|
8 | 16 | public MetricsContainer(string[] metrics, string[] output_names = null) |
9 | 17 | : base(output_names) |
10 | 18 | { |
11 | 19 | _user_metrics = metrics; |
12 | | - _metrics = metrics; |
| 20 | + _metric_names = metrics; |
13 | 21 | _built = false; |
14 | 22 | } |
15 | 23 |
|
16 | 24 | public void update_state(Tensor y_true, Tensor y_pred, Tensor sample_weight = null) |
17 | 25 | { |
18 | 26 | if (!_built) |
19 | | - Build(); |
| 27 | + Build(y_true, y_pred); |
| 28 | + |
| 29 | + foreach (var metric_obj in _metrics_in_order) |
| 30 | + metric_obj.update_state(y_true, y_pred); |
| 31 | + } |
20 | 32 |
|
| 33 | + void Build(Tensor y_true, Tensor y_pred) |
| 34 | + { |
| 35 | + _metrics = _get_metric_objects(_metric_names, y_true, y_pred); |
| 36 | + _set_metric_names(); |
| 37 | + _create_ordered_metrics(); |
21 | 38 | _built = true; |
22 | 39 | } |
23 | 40 |
|
24 | | - void Build() |
| 41 | + void _set_metric_names() |
| 42 | + { |
| 43 | + |
| 44 | + } |
| 45 | + |
| 46 | + void _create_ordered_metrics() |
| 47 | + { |
| 48 | + _metrics_in_order = new List<Metric>(); |
| 49 | + foreach (var m in _metrics) |
| 50 | + _metrics_in_order.append(m); |
| 51 | + } |
| 52 | + |
| 53 | + Metric[] _get_metric_objects(string[] metrics, Tensor y_t, Tensor y_p) |
| 54 | + { |
| 55 | + return metrics.Select(x => _get_metric_object(x, y_t, y_p)).ToArray(); |
| 56 | + } |
| 57 | + |
| 58 | + Metric _get_metric_object(string metric, Tensor y_t, Tensor y_p) |
| 59 | + { |
| 60 | + Func<Tensor, Tensor, Tensor> metric_obj = null; |
| 61 | + if (metric == "accuracy" || metric == "acc") |
| 62 | + { |
| 63 | + metric_obj = tf.keras.metrics.sparse_categorical_accuracy; |
| 64 | + return new MeanMetricWrapper(metric_obj, metric); |
| 65 | + } |
| 66 | + |
| 67 | + throw new NotImplementedException(""); |
| 68 | + } |
| 69 | + |
| 70 | + public IEnumerable<Metric> metrics |
25 | 71 | { |
| 72 | + get |
| 73 | + { |
| 74 | + if (!_built) |
| 75 | + return new List<Metric>(); |
26 | 76 |
|
| 77 | + return _metrics_in_order; |
| 78 | + } |
27 | 79 | } |
28 | 80 | } |
29 | 81 | } |
0 commit comments