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.9 kB

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