Skip to content

Commit 217cfd2

Browse files
committed
Add mertic of Recall.
1 parent a5289b9 commit 217cfd2

10 files changed

Lines changed: 269 additions & 8 deletions

File tree

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,15 @@ public interface IMetricsApi
3535
/// <param name="k"></param>
3636
/// <returns></returns>
3737
IMetricFunc TopKCategoricalAccuracy(int k = 5, string name = "top_k_categorical_accuracy", TF_DataType dtype = TF_DataType.TF_FLOAT);
38+
39+
/// <summary>
40+
/// Computes the recall of the predictions with respect to the labels.
41+
/// </summary>
42+
/// <param name="thresholds"></param>
43+
/// <param name="top_k"></param>
44+
/// <param name="class_id"></param>
45+
/// <param name="name"></param>
46+
/// <param name="dtype"></param>
47+
/// <returns></returns>
48+
IMetricFunc Recall(float thresholds = 0.5f, int top_k = 1, int class_id = 0, string name = "recall", TF_DataType dtype = TF_DataType.TF_FLOAT);
3849
}

‎src/TensorFlowNET.Core/Operations/array_ops.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,9 @@ private static TF_DataType _get_dtype_from_nested_lists<T>(IEnumerable<T> list_o
221221
case Tensor t:
222222
dtype = t.dtype.as_base_dtype();
223223
break;
224+
case int t:
225+
dtype = TF_DataType.TF_INT32;
226+
break;
224227
}
225228

226229
if (dtype != TF_DataType.DtInvalid)
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
global using System;
22
global using System.Collections.Generic;
33
global using System.Text;
4+
global using System.Linq;
45
global using static Tensorflow.Binding;
5-
global using static Tensorflow.KerasApi;
6+
global using static Tensorflow.KerasApi;
7+
global using Tensorflow.NumPy;

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public override Tensor update_state(Tensor y_true, Tensor y_pred, Tensor sample_
1818
y_true = math_ops.cast(y_true, _dtype);
1919
y_pred = math_ops.cast(y_pred, _dtype);
2020

21-
(y_pred, y_true) = losses_utils.squeeze_or_expand_dimensions(y_pred, y_true: y_true);
21+
(y_pred, y_true, _) = losses_utils.squeeze_or_expand_dimensions(y_pred, y_true: y_true);
2222

2323
var matches = _fn(y_true, y_pred);
2424
return update_state(matches, sample_weight: sample_weight);

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,5 +61,8 @@ public Tensor top_k_categorical_accuracy(Tensor y_true, Tensor y_pred, int k = 5
6161

6262
public IMetricFunc TopKCategoricalAccuracy(int k = 5, string name = "top_k_categorical_accuracy", TF_DataType dtype = TF_DataType.TF_FLOAT)
6363
=> new TopKCategoricalAccuracy(k: k, name: name, dtype: dtype);
64+
65+
public IMetricFunc Recall(float thresholds = 0.5f, int top_k = 1, int class_id = 0, string name = "recall", TF_DataType dtype = TF_DataType.TF_FLOAT)
66+
=> new Recall(thresholds: thresholds, top_k: top_k, class_id: class_id, name: name, dtype: dtype);
6467
}
6568
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
namespace Tensorflow.Keras.Metrics;
2+
3+
public class Recall : Metric
4+
{
5+
Tensor _thresholds;
6+
int _top_k;
7+
int _class_id;
8+
IVariableV1 true_positives;
9+
IVariableV1 false_negatives;
10+
bool _thresholds_distributed_evenly;
11+
12+
public Recall(float thresholds = 0.5f, int top_k = 1, int class_id = 0, string name = "recall", TF_DataType dtype = TF_DataType.TF_FLOAT)
13+
: base(name: name, dtype: dtype)
14+
{
15+
_thresholds = constant_op.constant(new float[] { thresholds });
16+
true_positives = add_weight("true_positives", shape: 1, initializer: tf.initializers.zeros_initializer());
17+
false_negatives = add_weight("false_negatives", shape: 1, initializer: tf.initializers.zeros_initializer());
18+
}
19+
20+
public override Tensor update_state(Tensor y_true, Tensor y_pred, Tensor sample_weight = null)
21+
{
22+
return metrics_utils.update_confusion_matrix_variables(
23+
new Dictionary<string, IVariableV1>
24+
{
25+
{ "tp", true_positives },
26+
{ "fn", false_negatives },
27+
},
28+
y_true,
29+
y_pred,
30+
thresholds: _thresholds,
31+
thresholds_distributed_evenly: _thresholds_distributed_evenly,
32+
top_k: _top_k,
33+
class_id: _class_id,
34+
sample_weight: sample_weight);
35+
}
36+
37+
public override Tensor result()
38+
{
39+
var result = tf.divide(true_positives.AsTensor(), tf.add(true_positives, false_negatives));
40+
return _thresholds.size == 1 ? result[0] : result;
41+
}
42+
43+
public override void reset_states()
44+
{
45+
var num_thresholds = (int)_thresholds.size;
46+
keras.backend.batch_set_value(
47+
new List<(IVariableV1, NDArray)>
48+
{
49+
(true_positives, np.zeros(num_thresholds)),
50+
(false_negatives, np.zeros(num_thresholds))
51+
});
52+
}
53+
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public Tensor update_state(Tensor values, Tensor sample_weight = null)
2727
{
2828
if (sample_weight != null)
2929
{
30-
(values, sample_weight) = losses_utils.squeeze_or_expand_dimensions(
30+
(values, _, sample_weight) = losses_utils.squeeze_or_expand_dimensions(
3131
values, sample_weight: sample_weight);
3232

3333
sample_weight = math_ops.cast(sample_weight, dtype: values.dtype);

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

Lines changed: 170 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using Tensorflow.NumPy;
1+
using Tensorflow.Keras.Utils;
2+
using Tensorflow.NumPy;
23

34
namespace Tensorflow.Keras.Metrics;
45

@@ -36,4 +37,172 @@ public static Tensor sparse_top_k_categorical_matches(Tensor y_true, Tensor y_pr
3637

3738
return matches;
3839
}
40+
41+
public static Tensor update_confusion_matrix_variables(Dictionary<string, IVariableV1> variables_to_update,
42+
Tensor y_true,
43+
Tensor y_pred,
44+
Tensor thresholds,
45+
int top_k,
46+
int class_id,
47+
Tensor sample_weight = null,
48+
bool multi_label = false,
49+
Tensor label_weights = null,
50+
bool thresholds_distributed_evenly = false)
51+
{
52+
var variable_dtype = variables_to_update.Values.First().dtype;
53+
y_true = tf.cast(y_true, dtype: variable_dtype);
54+
y_pred = tf.cast(y_pred, dtype: variable_dtype);
55+
var num_thresholds = thresholds.shape.dims[0];
56+
57+
Tensor one_thresh = null;
58+
if (multi_label)
59+
{
60+
one_thresh = tf.equal(tf.cast(constant_op.constant(1), dtype:tf.int32),
61+
tf.rank(thresholds),
62+
name: "one_set_of_thresholds_cond");
63+
}
64+
else
65+
{
66+
one_thresh = tf.cast(constant_op.constant(true), dtype: dtypes.@bool);
67+
}
68+
69+
if (sample_weight == null)
70+
{
71+
(y_pred, y_true, _) = losses_utils.squeeze_or_expand_dimensions(y_pred, y_true);
72+
}
73+
else
74+
{
75+
sample_weight = tf.cast(sample_weight, dtype: variable_dtype);
76+
(y_pred, y_true, sample_weight) = losses_utils.squeeze_or_expand_dimensions(y_pred,
77+
y_true,
78+
sample_weight: sample_weight);
79+
}
80+
81+
if (thresholds_distributed_evenly)
82+
{
83+
throw new NotImplementedException();
84+
}
85+
86+
var pred_shape = tf.shape(y_pred);
87+
var num_predictions = pred_shape[0];
88+
89+
Tensor num_labels;
90+
if (y_pred.shape.ndim == 1)
91+
{
92+
num_labels = constant_op.constant(1);
93+
}
94+
else
95+
{
96+
num_labels = tf.reduce_prod(pred_shape["1:"], axis: 0);
97+
}
98+
var thresh_label_tile = tf.where(one_thresh, num_labels, tf.ones(new int[0], dtype: tf.int32));
99+
100+
// Reshape predictions and labels, adding a dim for thresholding.
101+
Tensor predictions_extra_dim, labels_extra_dim;
102+
if (multi_label)
103+
{
104+
predictions_extra_dim = tf.expand_dims(y_pred, 0);
105+
labels_extra_dim = tf.expand_dims(tf.cast(y_true, dtype: tf.@bool), 0);
106+
}
107+
108+
else
109+
{
110+
// Flatten predictions and labels when not multilabel.
111+
predictions_extra_dim = tf.reshape(y_pred, (1, -1));
112+
labels_extra_dim = tf.reshape(tf.cast(y_true, dtype: tf.@bool), (1, -1));
113+
}
114+
115+
// Tile the thresholds for every prediction.
116+
object[] thresh_pretile_shape, thresh_tiles, data_tiles;
117+
118+
if (multi_label)
119+
{
120+
thresh_pretile_shape = new object[] { num_thresholds, 1, -1 };
121+
thresh_tiles = new object[] { 1, num_predictions, thresh_label_tile };
122+
data_tiles = new object[] { num_thresholds, 1, 1 };
123+
}
124+
else
125+
{
126+
thresh_pretile_shape = new object[] { num_thresholds, -1 };
127+
thresh_tiles = new object[] { 1, num_predictions * num_labels };
128+
data_tiles = new object[] { num_thresholds, 1 };
129+
}
130+
var thresh_tiled = tf.tile(tf.reshape(thresholds, thresh_pretile_shape), tf.stack(thresh_tiles));
131+
132+
// Tile the predictions for every threshold.
133+
var preds_tiled = tf.tile(predictions_extra_dim, data_tiles);
134+
135+
// Compare predictions and threshold.
136+
var pred_is_pos = tf.greater(preds_tiled, thresh_tiled);
137+
138+
// Tile labels by number of thresholds
139+
var label_is_pos = tf.tile(labels_extra_dim, data_tiles);
140+
141+
Tensor weights_tiled = null;
142+
143+
if (sample_weight != null)
144+
{
145+
/*sample_weight = broadcast_weights(
146+
tf.cast(sample_weight, dtype: variable_dtype), y_pred);*/
147+
weights_tiled = tf.tile(
148+
tf.reshape(sample_weight, thresh_tiles), data_tiles);
149+
}
150+
151+
if (label_weights != null && !multi_label)
152+
{
153+
throw new NotImplementedException();
154+
}
155+
156+
Func<Tensor, Tensor, Tensor, IVariableV1, ITensorOrOperation> weighted_assign_add
157+
= (label, pred, weights, var) =>
158+
{
159+
var label_and_pred = tf.cast(tf.logical_and(label, pred), dtype: var.dtype);
160+
if (weights != null)
161+
{
162+
label_and_pred *= tf.cast(weights, dtype: var.dtype);
163+
}
164+
165+
return var.assign_add(tf.reduce_sum(label_and_pred, 1));
166+
};
167+
168+
169+
var loop_vars = new Dictionary<string, (Tensor, Tensor)>
170+
{
171+
{ "tp", (label_is_pos, pred_is_pos) }
172+
};
173+
var update_tn = variables_to_update.ContainsKey("tn");
174+
var update_fp = variables_to_update.ContainsKey("fp");
175+
var update_fn = variables_to_update.ContainsKey("fn");
176+
177+
Tensor pred_is_neg = null;
178+
if (update_fn || update_tn)
179+
{
180+
pred_is_neg = tf.logical_not(pred_is_pos);
181+
loop_vars["fn"] = (label_is_pos, pred_is_neg);
182+
}
183+
184+
if(update_fp || update_tn)
185+
{
186+
var label_is_neg = tf.logical_not(label_is_pos);
187+
loop_vars["fp"] = (label_is_neg, pred_is_pos);
188+
if (update_tn)
189+
{
190+
loop_vars["tn"] = (label_is_neg, pred_is_neg);
191+
}
192+
}
193+
194+
var update_ops = new List<ITensorOrOperation>();
195+
foreach (var matrix_cond in loop_vars.Keys)
196+
{
197+
var (label, pred) = loop_vars[matrix_cond];
198+
if (variables_to_update.ContainsKey(matrix_cond))
199+
{
200+
var op = weighted_assign_add(label, pred, weights_tiled, variables_to_update[matrix_cond]);
201+
update_ops.append(op);
202+
}
203+
}
204+
205+
tf.group(update_ops.ToArray());
206+
return null;
207+
}
39208
}

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public static Tensor compute_weighted_loss(Tensor losses, Tensor sample_weight =
3838
});
3939
}
4040

41-
public static (Tensor, Tensor) squeeze_or_expand_dimensions(Tensor y_pred, Tensor y_true = null, Tensor sample_weight = null)
41+
public static (Tensor, Tensor, Tensor) squeeze_or_expand_dimensions(Tensor y_pred, Tensor y_true = null, Tensor sample_weight = null)
4242
{
4343
var y_pred_shape = y_pred.shape;
4444
var y_pred_rank = y_pred_shape.ndim;
@@ -57,13 +57,13 @@ public static (Tensor, Tensor) squeeze_or_expand_dimensions(Tensor y_pred, Tenso
5757

5858
if (sample_weight == null)
5959
{
60-
return (y_pred, y_true);
60+
return (y_pred, y_true, sample_weight);
6161
}
6262

6363
var weights_shape = sample_weight.shape;
6464
var weights_rank = weights_shape.ndim;
6565
if (weights_rank == 0)
66-
return (y_pred, sample_weight);
66+
return (y_pred, y_true, sample_weight);
6767

6868
if (y_pred_rank > -1 && weights_rank > -1)
6969
{
@@ -77,7 +77,7 @@ public static (Tensor, Tensor) squeeze_or_expand_dimensions(Tensor y_pred, Tenso
7777
}
7878
else
7979
{
80-
return (y_pred, sample_weight);
80+
return (y_pred, y_true, sample_weight);
8181
}
8282
}
8383

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,24 @@ public void top_k_categorical_accuracy()
4545
var m = tf.keras.metrics.top_k_categorical_accuracy(y_true, y_pred, k: 3);
4646
Assert.AreEqual(m.numpy(), new[] { 1f, 1f });
4747
}
48+
49+
/// <summary>
50+
/// https://www.tensorflow.org/api_docs/python/tf/keras/metrics/Recall
51+
/// </summary>
52+
[TestMethod]
53+
public void Recall()
54+
{
55+
var y_true = np.array(new[] { 0, 1, 1, 1 });
56+
var y_pred = np.array(new[] { 1, 0, 1, 1 });
57+
var m = tf.keras.metrics.Recall();
58+
m.update_state(y_true, y_pred);
59+
var r = m.result().numpy();
60+
Assert.AreEqual(r, 0.6666667f);
61+
62+
m.reset_states();
63+
var weights = np.array(new[] { 0f, 0f, 1f, 0f });
64+
m.update_state(y_true, y_pred, sample_weight: weights);
65+
r = m.result().numpy();
66+
Assert.AreEqual(r, 1f);
67+
}
4868
}

0 commit comments

Comments
 (0)