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.

GradientEagerTest.cs 1.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Microsoft.VisualStudio.TestTools.UnitTesting;
  5. using Tensorflow;
  6. using static Tensorflow.Binding;
  7. namespace TensorFlowNET.UnitTest.Gradient
  8. {
  9. [TestClass]
  10. public class GradientEagerTest : PythonTest
  11. {
  12. [TestMethod]
  13. public void ConstantSquare()
  14. {
  15. // Calcute the gradient of w * w
  16. // by Automatic Differentiation in Eager mode
  17. // in tensorflow.net 2.x that is in development intensively
  18. var w = tf.constant(1.5f);
  19. using var tape = tf.GradientTape();
  20. tape.watch(w);
  21. var loss = w * w;
  22. var grad = tape.gradient(loss, w);
  23. Assert.AreEqual((float)grad, 3.0f);
  24. }
  25. [TestMethod]
  26. public void ConstantMultiply()
  27. {
  28. var x = tf.ones((2, 2));
  29. using var tape = tf.GradientTape();
  30. tape.watch(x);
  31. var y = tf.reduce_sum(x);
  32. var z = tf.multiply(y, y);
  33. var dz_dx = tape.gradient(z, x);
  34. var expected = new float[] { 8.0f, 8.0f, 8.0f, 8.0f };
  35. Assert.IsTrue(Enumerable.SequenceEqual(dz_dx.ToArray<float>(), expected));
  36. }
  37. [TestMethod]
  38. public void PersistentTape()
  39. {
  40. var x = tf.ones((2, 2));
  41. using var tape = tf.GradientTape(persistent: true);
  42. tape.watch(x);
  43. var y = tf.reduce_sum(x);
  44. var z = tf.multiply(y, y);
  45. var dz_dx = tape.gradient(z, x);
  46. var expected = new float[] { 8.0f, 8.0f, 8.0f, 8.0f };
  47. Assert.IsTrue(Enumerable.SequenceEqual(dz_dx.ToArray<float>(), expected));
  48. var dz_dy = tape.gradient(z, y);
  49. expected = new float[] { 8.0f, 8.0f, 8.0f, 8.0f };
  50. Assert.IsTrue(Enumerable.SequenceEqual(dz_dx.ToArray<float>(), expected));
  51. }
  52. }
  53. }