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

1234567891011121314151617181920212223242526272829303132333435363738394041
  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.numpy().ToArray<float>(), expected));
  36. }
  37. }
  38. }