triplet_loss_test.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # MIT License
  2. #
  3. # Copyright (c) 2016 David Sandberg
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in all
  13. # copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. import unittest
  23. import tensorflow as tf
  24. import numpy as np
  25. import facenet
  26. class DemuxEmbeddingsTest(unittest.TestCase):
  27. def testDemuxEmbeddings(self):
  28. batch_size = 3*12
  29. embedding_size = 16
  30. alpha = 0.2
  31. with tf.Graph().as_default():
  32. embeddings = tf.placeholder(tf.float64, shape=(batch_size, embedding_size), name='embeddings')
  33. anchor, positive, negative = tf.unstack(tf.reshape(embeddings, [-1,3,embedding_size]), 3, 1)
  34. triplet_loss = facenet.triplet_loss(anchor, positive, negative, alpha)
  35. sess = tf.Session()
  36. with sess.as_default():
  37. np.random.seed(seed=666)
  38. emb = np.random.uniform(size=(batch_size, embedding_size))
  39. tf_triplet_loss = sess.run(triplet_loss, feed_dict={embeddings:emb})
  40. pos_dist_sqr = np.sum(np.square(emb[0::3,:]-emb[1::3,:]),1)
  41. neg_dist_sqr = np.sum(np.square(emb[0::3,:]-emb[2::3,:]),1)
  42. np_triplet_loss = np.mean(np.maximum(0.0, pos_dist_sqr - neg_dist_sqr + alpha))
  43. np.testing.assert_almost_equal(tf_triplet_loss, np_triplet_loss, decimal=5, err_msg='Triplet loss is incorrect')
  44. if __name__ == "__main__":
  45. unittest.main()