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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. [TestMethod]
  23. public void testZeroFraction()
  24. {
  25. var x_shape = new Shape(5, 17);
  26. var x_np = np.random.randint(0, 2, x_shape);
  27. //x_np.astype(np.float32);
  28. var y_np = this._ZeroFraction(x_np);
  29. var x_tf = constant_op.constant(x_np);
  30. x_tf.SetShape(x_shape);
  31. var y_tf = nn_impl.zero_fraction(x_tf);
  32. var y_tf_np = self.evaluate<NDArray>(y_tf);
  33. var eps = 1e-8;
  34. self.assertAllClose(y_tf_np, y_np, eps);
  35. }
  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. [TestMethod]
  52. public void testZeroFraction2_27Ones()
  53. {
  54. var sparsity = nn_impl.zero_fraction(
  55. array_ops.ones(new Shape((int)Math.Pow(2, 27 * 1.01)), dtypes.int8));
  56. self.assertAllClose(0.0, self.evaluate<NDArray>(sparsity));
  57. }
  58. [Ignore("TODO implement nn_impl.zero_fraction")]
  59. [TestMethod]
  60. public void testUnknownSize()
  61. {
  62. var value = array_ops.placeholder(dtype: dtypes.float32);
  63. var sparsity = nn_impl.zero_fraction(value);
  64. with<Session>(self.cached_session(), sess => {
  65. // TODO: make this compile
  66. //self.assertAllClose(
  67. // 0.25,
  68. // sess.run(sparsity, {value: [[0., 1.], [0.3, 2.]]}));
  69. });
  70. }
  71. }
  72. }