You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ZeroFractionTest.cs 2.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Linq;
  3. using Microsoft.VisualStudio.TestTools.UnitTesting;
  4. using NumSharp;
  5. using Tensorflow;
  6. using static Tensorflow.Binding;
  7. namespace TensorFlowNET.UnitTest.nn_test
  8. {
  9. [TestClass]
  10. public class ZeroFractionTest : PythonTest
  11. {
  12. protected double _ZeroFraction(NDArray x)
  13. {
  14. assert(x.shape);
  15. int total_elements = np.prod(x.shape);
  16. var eps = 1e-8;
  17. var nonzeros = x.Data<double>().Count(d=>Math.Abs(d)> eps);
  18. return 1.0 - nonzeros / (double)total_elements;
  19. }
  20. [Ignore("TODO implement nn_impl.zero_fraction")]
  21. [TestMethod]
  22. public void testZeroFraction()
  23. {
  24. var x_shape = new Shape(5, 17);
  25. var x_np = np.random.randint(0, 2, x_shape);
  26. //x_np.astype(np.float32);
  27. var y_np = this._ZeroFraction(x_np);
  28. var x_tf = constant_op.constant(x_np);
  29. x_tf.set_shape(x_shape);
  30. var y_tf = nn_impl.zero_fraction(x_tf);
  31. var y_tf_np = self.evaluate<NDArray>(y_tf);
  32. var eps = 1e-8;
  33. self.assertAllClose(y_tf_np, y_np, eps);
  34. }
  35. [Ignore("TODO implement nn_impl.zero_fraction")]
  36. [TestMethod]
  37. public void testZeroFractionEmpty()
  38. {
  39. var x = np.zeros(0);
  40. var y = self.evaluate<NDArray>(nn_impl.zero_fraction(new Tensor(x)));
  41. self.assertTrue(np.isnan(y));
  42. }
  43. [Ignore("TODO implement nn_impl.zero_fraction")]
  44. [TestMethod]
  45. public void testZeroFraction2_27Zeros()
  46. {
  47. var sparsity = nn_impl.zero_fraction(
  48. array_ops.zeros(new Shape((int) Math.Pow(2, 27 * 1.01)), dtypes.int8));
  49. self.assertAllClose(1.0, self.evaluate<NDArray>(sparsity));
  50. }
  51. [Ignore("TODO implement nn_impl.zero_fraction")]
  52. [TestMethod]
  53. public void testZeroFraction2_27Ones()
  54. {
  55. var sparsity = nn_impl.zero_fraction(
  56. array_ops.ones(new TensorShape((int)Math.Pow(2, 27 * 1.01)), dtypes.int8));
  57. self.assertAllClose(0.0, self.evaluate<NDArray>(sparsity));
  58. }
  59. [Ignore("TODO implement nn_impl.zero_fraction")]
  60. [TestMethod]
  61. public void testUnknownSize()
  62. {
  63. var value = array_ops.placeholder(dtype: dtypes.float32);
  64. var sparsity = nn_impl.zero_fraction(value);
  65. using (var sess = self.cached_session())
  66. {
  67. // TODO: make this compile
  68. //self.assertAllClose(
  69. // 0.25,
  70. // sess.run(sparsity, {value: [[0., 1.], [0.3, 2.]]}));
  71. }
  72. }
  73. }
  74. }