Skip to content
This repository was archived by the owner on Jul 1, 2023. It is now read-only.

Add Triplet loss function #31

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Sources/DeepLearning/Loss.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,21 @@ public func sigmoidCrossEntropy<Scalar: TensorFlowFloatingPoint>(
(Tensor<Scalar>(1) - labels) * log(Tensor<Scalar>(1) - logits)
return -loss.mean(alongAxes: 0).sum()
}

/// Computes the triplet loss.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// Computes the triplet loss.
/// Returns the triplet loss.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also add the citation as Anthony suggested.

///
/// - Parameters:
/// - anchor: Encoding for the anchor data.
/// - positive: Encoding for the positive data.
/// - negative: Encoding for the negative data.
/// - margin: Contrastive margin.
@differentiable
public func triplet<Scalar: TensorFlowFloatingPoint>(
anchor: Tensor<Scalar>, positive: Tensor<Scalar>,
negative: Tensor<Scalar>, margin: Tensor<Scalar>
) -> Tensor<Scalar> {
let positiveDistance = (anchor - positive).squared().sum(alongAxes: 1)
let negativeDistance = (anchor - negative).squared().sum(alongAxes: 1)
let loss = positiveDistance - negativeDistance + margin
return max(loss.mean(), Tensor<Scalar>(0))
}