Skip to content

Commit a5289b9

Browse files
committed
Abstract IMetricFunc.
1 parent ca9f574 commit a5289b9

8 files changed

Lines changed: 110 additions & 5 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
namespace Tensorflow.Keras.Metrics;
2+
3+
public interface IMetricFunc
4+
{
5+
/// <summary>
6+
/// Accumulates metric statistics.
7+
/// </summary>
8+
/// <param name="y_true"></param>
9+
/// <param name="y_pred"></param>
10+
/// <param name="sample_weight"></param>
11+
/// <returns></returns>
12+
Tensor update_state(Tensor y_true, Tensor y_pred, Tensor sample_weight = null);
13+
14+
Tensor result();
15+
16+
void reset_states();
17+
}

‎src/TensorFlowNET.Core/Keras/Metrics/IMetricsApi.cs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,13 @@ public interface IMetricsApi
2626
/// <param name="k"></param>
2727
/// <returns></returns>
2828
Tensor top_k_categorical_accuracy(Tensor y_true, Tensor y_pred, int k = 5);
29+
30+
/// <summary>
31+
/// Computes how often targets are in the top K predictions.
32+
/// </summary>
33+
/// <param name="y_true"></param>
34+
/// <param name="y_pred"></param>
35+
/// <param name="k"></param>
36+
/// <returns></returns>
37+
IMetricFunc TopKCategoricalAccuracy(int k = 5, string name = "top_k_categorical_accuracy", TF_DataType dtype = TF_DataType.TF_FLOAT);
2938
}

‎src/TensorFlowNET.Keras/Metrics/MeanMetricWrapper.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using Tensorflow.Keras.Utils;
23

34
namespace Tensorflow.Keras.Metrics
45
{
@@ -17,6 +18,8 @@ public override Tensor update_state(Tensor y_true, Tensor y_pred, Tensor sample_
1718
y_true = math_ops.cast(y_true, _dtype);
1819
y_pred = math_ops.cast(y_pred, _dtype);
1920

21+
(y_pred, y_true) = losses_utils.squeeze_or_expand_dimensions(y_pred, y_true: y_true);
22+
2023
var matches = _fn(y_true, y_pred);
2124
return update_state(matches, sample_weight: sample_weight);
2225
}

‎src/TensorFlowNET.Keras/Metrics/Metric.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ namespace Tensorflow.Keras.Metrics
99
/// <summary>
1010
/// Encapsulates metric logic and state.
1111
/// </summary>
12-
public class Metric : Layer
12+
public class Metric : Layer, IMetricFunc
1313
{
1414
protected IVariableV1 total;
1515
protected IVariableV1 count;

‎src/TensorFlowNET.Keras/Metrics/MetricsApi.cs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using static Tensorflow.KerasApi;
2-
3-
namespace Tensorflow.Keras.Metrics
1+
namespace Tensorflow.Keras.Metrics
42
{
53
public class MetricsApi : IMetricsApi
64
{
@@ -60,5 +58,8 @@ public Tensor top_k_categorical_accuracy(Tensor y_true, Tensor y_pred, int k = 5
6058
tf.math.argmax(y_true, axis: -1), y_pred, k
6159
);
6260
}
61+
62+
public IMetricFunc TopKCategoricalAccuracy(int k = 5, string name = "top_k_categorical_accuracy", TF_DataType dtype = TF_DataType.TF_FLOAT)
63+
=> new TopKCategoricalAccuracy(k: k, name: name, dtype: dtype);
6364
}
6465
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
namespace Tensorflow.Keras.Metrics;
2+
3+
public class TopKCategoricalAccuracy : MeanMetricWrapper
4+
{
5+
public TopKCategoricalAccuracy(int k = 5, string name = "top_k_categorical_accuracy", TF_DataType dtype = TF_DataType.TF_FLOAT)
6+
: base((yt, yp) => metrics_utils.sparse_top_k_categorical_matches(
7+
tf.math.argmax(yt, axis: -1), yp, k),
8+
name: name,
9+
dtype: dtype)
10+
{
11+
}
12+
}

‎src/TensorFlowNET.Keras/Utils/losses_utils.cs‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ limitations under the License.
1515
******************************************************************************/
1616

1717
using System;
18+
using System.Xml.Linq;
1819
using Tensorflow.Keras.Losses;
1920
using static Tensorflow.Binding;
2021

@@ -37,15 +38,57 @@ public static Tensor compute_weighted_loss(Tensor losses, Tensor sample_weight =
3738
});
3839
}
3940

40-
public static (Tensor, Tensor) squeeze_or_expand_dimensions(Tensor y_pred, Tensor sample_weight)
41+
public static (Tensor, Tensor) squeeze_or_expand_dimensions(Tensor y_pred, Tensor y_true = null, Tensor sample_weight = null)
4142
{
43+
var y_pred_shape = y_pred.shape;
44+
var y_pred_rank = y_pred_shape.ndim;
45+
if (y_true != null)
46+
{
47+
var y_true_shape = y_true.shape;
48+
var y_true_rank = y_true_shape.ndim;
49+
if (y_true_rank > -1 && y_pred_rank > -1)
50+
{
51+
if (y_pred_rank - y_true_rank != 1 || y_pred_shape[-1] == 1)
52+
{
53+
(y_true, y_pred) = remove_squeezable_dimensions(y_true, y_pred);
54+
}
55+
}
56+
}
57+
58+
if (sample_weight == null)
59+
{
60+
return (y_pred, y_true);
61+
}
62+
4263
var weights_shape = sample_weight.shape;
4364
var weights_rank = weights_shape.ndim;
4465
if (weights_rank == 0)
4566
return (y_pred, sample_weight);
67+
68+
if (y_pred_rank > -1 && weights_rank > -1)
69+
{
70+
if (weights_rank - y_pred_rank == 1)
71+
{
72+
sample_weight = tf.squeeze(sample_weight, -1);
73+
}
74+
else if (y_pred_rank - weights_rank == 1)
75+
{
76+
sample_weight = tf.expand_dims(sample_weight, -1);
77+
}
78+
else
79+
{
80+
return (y_pred, sample_weight);
81+
}
82+
}
83+
4684
throw new NotImplementedException("");
4785
}
4886

87+
public static (Tensor, Tensor) remove_squeezable_dimensions(Tensor labels, Tensor predictions, int expected_rank_diff = 0, string name = null)
88+
{
89+
return (labels, predictions);
90+
}
91+
4992
public static Tensor reduce_weighted_loss(Tensor weighted_losses, string reduction)
5093
{
5194
if (reduction == ReductionV2.NONE)

‎test/TensorFlowNET.Keras.UnitTest/Metrics/MetricsTest.cs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,26 @@ namespace TensorFlowNET.Keras.UnitTest;
1414
[TestClass]
1515
public class MetricsTest : EagerModeTestBase
1616
{
17+
/// <summary>
18+
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/TopKCategoricalAccuracy
19+
/// </summary>
20+
[TestMethod]
21+
public void TopKCategoricalAccuracy()
22+
{
23+
var y_true = np.array(new[,] { { 0, 0, 1 }, { 0, 1, 0 } });
24+
var y_pred = np.array(new[,] { { 0.1f, 0.9f, 0.8f }, { 0.05f, 0.95f, 0f } });
25+
var m = tf.keras.metrics.TopKCategoricalAccuracy(k: 1);
26+
m.update_state(y_true, y_pred);
27+
var r = m.result().numpy();
28+
Assert.AreEqual(r, 0.5f);
29+
30+
m.reset_states();
31+
var weights = np.array(new[] { 0.7f, 0.3f });
32+
m.update_state(y_true, y_pred, sample_weight: weights);
33+
r = m.result().numpy();
34+
Assert.AreEqual(r, 0.3f);
35+
}
36+
1737
/// <summary>
1838
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/top_k_categorical_accuracy
1939
/// </summary>

0 commit comments

Comments
 (0)