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.

LossesTest.cs 2.6 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using Microsoft.VisualStudio.TestTools.UnitTesting;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Tensorflow;
  8. using Tensorflow.NumPy;
  9. using TensorFlowNET.Keras.UnitTest;
  10. using static Tensorflow.Binding;
  11. using static Tensorflow.KerasApi;
  12. namespace TensorFlowNET.Keras.UnitTest;
  13. [TestClass]
  14. public class LossesTest : EagerModeTestBase
  15. {
  16. /// <summary>
  17. /// https://www.tensorflow.org/api_docs/python/tf/keras/losses/BinaryCrossentropy
  18. /// </summary>
  19. [TestMethod]
  20. public void BinaryCrossentropy()
  21. {
  22. // Example 1: (batch_size = 1, number of samples = 4)
  23. var y_true = tf.constant(new float[] { 0, 1, 0, 0 });
  24. var y_pred = tf.constant(new float[] { -18.6f, 0.51f, 2.94f, -12.8f });
  25. var bce = tf.keras.losses.BinaryCrossentropy(from_logits: true);
  26. var loss = bce.Call(y_true, y_pred);
  27. Assert.AreEqual((float)loss, 0.865458f);
  28. // Example 2: (batch_size = 2, number of samples = 4)
  29. y_true = tf.constant(new float[,] { { 0, 1 }, { 0, 0 } });
  30. y_pred = tf.constant(new float[,] { { -18.6f, 0.51f }, { 2.94f, -12.8f } });
  31. bce = tf.keras.losses.BinaryCrossentropy(from_logits: true);
  32. loss = bce.Call(y_true, y_pred);
  33. Assert.AreEqual((float)loss, 0.865458f);
  34. // Using 'sample_weight' attribute
  35. loss = bce.Call(y_true, y_pred, sample_weight: tf.constant(new[] { 0.8f, 0.2f }));
  36. Assert.AreEqual((float)loss, 0.2436386f);
  37. // Using 'sum' reduction` type.
  38. bce = tf.keras.losses.BinaryCrossentropy(from_logits: true, reduction: Reduction.SUM);
  39. loss = bce.Call(y_true, y_pred);
  40. Assert.AreEqual((float)loss, 1.730916f);
  41. // Using 'none' reduction type.
  42. bce = tf.keras.losses.BinaryCrossentropy(from_logits: true, reduction: Reduction.NONE);
  43. loss = bce.Call(y_true, y_pred);
  44. Assert.AreEqual(new float[] { 0.23515666f, 1.4957594f}, loss.numpy());
  45. }
  46. /// <summary>
  47. /// https://www.tensorflow.org/addons/api_docs/python/tfa/losses/SigmoidFocalCrossEntropy
  48. /// </summary>
  49. [TestMethod]
  50. public void SigmoidFocalCrossEntropy()
  51. {
  52. var y_true = np.expand_dims(np.array(new[] { 1.0f, 1.0f, 0 }));
  53. var y_pred = np.expand_dims(np.array(new[] { 0.97f, 0.91f, 0.03f }));
  54. var bce = tf.keras.losses.SigmoidFocalCrossEntropy();
  55. var loss = bce.Call(y_true, y_pred);
  56. Assert.AreEqual(new[] { 6.8532745e-06f, 1.909787e-04f, 2.0559824e-05f }, loss.numpy());
  57. }
  58. }