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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 TensorFlowNET.Keras.UnitTest;
  9. using static Tensorflow.Binding;
  10. using static Tensorflow.KerasApi;
  11. namespace TensorFlowNET.Keras.UnitTest;
  12. [TestClass]
  13. public class LossesTest : EagerModeTestBase
  14. {
  15. /// <summary>
  16. /// https://www.tensorflow.org/api_docs/python/tf/keras/losses/BinaryCrossentropy
  17. /// </summary>
  18. [TestMethod]
  19. public void BinaryCrossentropy()
  20. {
  21. // Example 1: (batch_size = 1, number of samples = 4)
  22. var y_true = tf.constant(new float[] { 0, 1, 0, 0 });
  23. var y_pred = tf.constant(new float[] { -18.6f, 0.51f, 2.94f, -12.8f });
  24. var bce = tf.keras.losses.BinaryCrossentropy(from_logits: true);
  25. var loss = bce.Call(y_true, y_pred);
  26. Assert.AreEqual((float)loss, 0.865458f);
  27. // Example 2: (batch_size = 2, number of samples = 4)
  28. y_true = tf.constant(new float[,] { { 0, 1 }, { 0, 0 } });
  29. y_pred = tf.constant(new float[,] { { -18.6f, 0.51f }, { 2.94f, -12.8f } });
  30. bce = tf.keras.losses.BinaryCrossentropy(from_logits: true);
  31. loss = bce.Call(y_true, y_pred);
  32. Assert.AreEqual((float)loss, 0.865458f);
  33. // Using 'sample_weight' attribute
  34. loss = bce.Call(y_true, y_pred, sample_weight: tf.constant(new[] { 0.8f, 0.2f }));
  35. Assert.AreEqual((float)loss, 0.2436386f);
  36. // Using 'sum' reduction` type.
  37. bce = tf.keras.losses.BinaryCrossentropy(from_logits: true, reduction: Reduction.SUM);
  38. loss = bce.Call(y_true, y_pred);
  39. Assert.AreEqual((float)loss, 1.730916f);
  40. // Using 'none' reduction type.
  41. bce = tf.keras.losses.BinaryCrossentropy(from_logits: true, reduction: Reduction.NONE);
  42. loss = bce.Call(y_true, y_pred);
  43. Assert.AreEqual(new float[] { 0.23515666f, 1.4957594f}, loss.numpy());
  44. }
  45. }