From a880b5326da7a3d6e42e5156293d31d5e702eae0 Mon Sep 17 00:00:00 2001 From: Antonio Date: Thu, 25 Jul 2019 23:38:06 +0200 Subject: [PATCH] Adding `IsNan` operation (#315) Exposing also the `IsFinite` one. Unit testing both operations. --- src/TensorFlowNET.Core/APIs/tf.math.cs | 6 ++++ .../Operations/gen_math_ops.cs | 7 +++++ test/TensorFlowNET.UnitTest/OperationsTest.cs | 28 +++++++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/src/TensorFlowNET.Core/APIs/tf.math.cs b/src/TensorFlowNET.Core/APIs/tf.math.cs index f18ece8c..d3b24373 100644 --- a/src/TensorFlowNET.Core/APIs/tf.math.cs +++ b/src/TensorFlowNET.Core/APIs/tf.math.cs @@ -57,6 +57,12 @@ namespace Tensorflow public static Tensor arg_min(Tensor input, int dimension, TF_DataType output_type = TF_DataType.TF_INT64, string name = null) => gen_math_ops.arg_min(input, dimension, output_type: output_type, name: name); + public static Tensor is_finite(Tensor input, string name = null) + => gen_math_ops.is_finite(input, name); + + public static Tensor is_nan(Tensor input, string name = null) + => gen_math_ops.is_nan(input, name); + /// /// Returns element-wise smallest integer not less than x. /// diff --git a/src/TensorFlowNET.Core/Operations/gen_math_ops.cs b/src/TensorFlowNET.Core/Operations/gen_math_ops.cs index 0999ad59..7ab6f858 100644 --- a/src/TensorFlowNET.Core/Operations/gen_math_ops.cs +++ b/src/TensorFlowNET.Core/Operations/gen_math_ops.cs @@ -376,6 +376,13 @@ namespace Tensorflow return _op.outputs[0]; } + public static Tensor is_nan(Tensor x, string name = null) + { + var _op = _op_def_lib._apply_op_helper("IsNan", name: name, args: new { x }); + + return _op.outputs[0]; + } + /// /// Computes exponential of x element-wise. \\(y = e^x\\). /// diff --git a/test/TensorFlowNET.UnitTest/OperationsTest.cs b/test/TensorFlowNET.UnitTest/OperationsTest.cs index 0359e4c3..7f099fde 100644 --- a/test/TensorFlowNET.UnitTest/OperationsTest.cs +++ b/test/TensorFlowNET.UnitTest/OperationsTest.cs @@ -61,6 +61,34 @@ namespace TensorFlowNET.UnitTest } } + [TestMethod] + public void isFinite() + { + var a = tf.constant(new[] { 1, np.nan, 2, np.nan, 3, np.nan, 4, np.nan }); + var b = tf.cast(tf.is_finite(a), tf.float32); + var check = np.array(1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); + + using (var sess = tf.Session()) + { + var o = sess.run(b); + Assert.IsTrue(o.array_equal(check)); + } + } + + [TestMethod] + public void isNan() + { + var a = tf.constant(new[] { 1, np.nan, 2, np.nan, 3, np.nan, 4, np.nan }); + var b = tf.cast(tf.is_nan(a), tf.float32); + var check = np.array(0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f); + + using (var sess = tf.Session()) + { + var o = sess.run(b); + Assert.IsTrue(o.array_equal(check)); + } + } + [TestMethod] public void addOpTests() {