outputLayer.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import * as tf from '@tensorflow/tfjs-core';
  2. function getCenterCoordinatesAndSizesLayer(x) {
  3. var vec = tf.unstack(tf.transpose(x, [1, 0]));
  4. var sizes = [
  5. tf.sub(vec[2], vec[0]),
  6. tf.sub(vec[3], vec[1])
  7. ];
  8. var centers = [
  9. tf.add(vec[0], tf.div(sizes[0], tf.scalar(2))),
  10. tf.add(vec[1], tf.div(sizes[1], tf.scalar(2)))
  11. ];
  12. return {
  13. sizes: sizes,
  14. centers: centers
  15. };
  16. }
  17. function decodeBoxesLayer(x0, x1) {
  18. var _a = getCenterCoordinatesAndSizesLayer(x0), sizes = _a.sizes, centers = _a.centers;
  19. var vec = tf.unstack(tf.transpose(x1, [1, 0]));
  20. var div0_out = tf.div(tf.mul(tf.exp(tf.div(vec[2], tf.scalar(5))), sizes[0]), tf.scalar(2));
  21. var add0_out = tf.add(tf.mul(tf.div(vec[0], tf.scalar(10)), sizes[0]), centers[0]);
  22. var div1_out = tf.div(tf.mul(tf.exp(tf.div(vec[3], tf.scalar(5))), sizes[1]), tf.scalar(2));
  23. var add1_out = tf.add(tf.mul(tf.div(vec[1], tf.scalar(10)), sizes[1]), centers[1]);
  24. return tf.transpose(tf.stack([
  25. tf.sub(add0_out, div0_out),
  26. tf.sub(add1_out, div1_out),
  27. tf.add(add0_out, div0_out),
  28. tf.add(add1_out, div1_out)
  29. ]), [1, 0]);
  30. }
  31. export function outputLayer(boxPredictions, classPredictions, params) {
  32. return tf.tidy(function () {
  33. var batchSize = boxPredictions.shape[0];
  34. var boxes = decodeBoxesLayer(tf.reshape(tf.tile(params.extra_dim, [batchSize, 1, 1]), [-1, 4]), tf.reshape(boxPredictions, [-1, 4]));
  35. boxes = tf.reshape(boxes, [batchSize, (boxes.shape[0] / batchSize), 4]);
  36. var scoresAndClasses = tf.sigmoid(tf.slice(classPredictions, [0, 0, 1], [-1, -1, -1]));
  37. var scores = tf.slice(scoresAndClasses, [0, 0, 0], [-1, -1, 1]);
  38. scores = tf.reshape(scores, [batchSize, scores.shape[1]]);
  39. var boxesByBatch = tf.unstack(boxes);
  40. var scoresByBatch = tf.unstack(scores);
  41. return {
  42. boxes: boxesByBatch,
  43. scores: scoresByBatch
  44. };
  45. });
  46. }
  47. //# sourceMappingURL=outputLayer.js.map