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

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