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

Add Cosine Similarity #233

Merged
merged 5 commits into from
Jun 13, 2019
Merged
Show file tree
Hide file tree
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
13 changes: 13 additions & 0 deletions Sources/TensorFlow/Loss.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,19 @@ public func hingeLoss<Scalar: TensorFlowFloatingPoint>(
return max(Tensor(1) - expected * predicted, Tensor(0)).mean()
}

/// Returns the cosine similarity between predictions and expectations.
///
/// - Parameters:
/// - predicted: Predicted outputs from a neural network.
/// - expected: Expected values, i.e. targets, that correspond to the correct output.
@differentiable(wrt: (predicted, expected))
public func cosineSimilarity<Scalar: TensorFlowFloatingPoint>(
predicted: Tensor<Scalar>, expected: Tensor<Scalar>
) -> Tensor<Scalar> {
return -(expected * predicted).sum() /
(sqrt(expected.squared().sum()) * sqrt(predicted.squared().sum()))
}

/// Returns the squared hinge loss between predictions and expectations.
///
/// - Parameters:
Expand Down
9 changes: 9 additions & 0 deletions Tests/TensorFlowTests/LossTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,14 @@ final class LossTests: XCTestCase {
let expectedLoss: Float = 0.225
assertElementsEqual(expected: Tensor(expectedLoss), actual: loss)
}

func testCosineSimilarityLoss() {
let predicted = Tensor<Float>([1, 2, 3, 4, 5, 6, 7, 8])
let expected = Tensor<Float>([0.5, 1, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0])
let loss = cosineSimilarity(predicted: predicted, expected: expected)
let expectedLoss: Float = -1.0
assertElementsEqual(expected: Tensor(expectedLoss), actual: loss)
}

func testSquaredHingeLoss() {
let predicted = Tensor<Float>([1, 2, 3, 4, 5, 6, 7, 8])
Expand Down Expand Up @@ -209,6 +217,7 @@ final class LossTests: XCTestCase {
("testHingeLoss", testHingeLoss),
("testKullbackLeiblerDivergence", testKullbackLeiblerDivergence),
("testCategoricalHingeLoss", testCategoricalHingeLoss),
("testCosineSimilarityLoss", testCosineSimilarityLoss),
("testSquaredHingeLoss", testSquaredHingeLoss),
("testPoissonLoss", testPoissonLoss),
("testSoftmaxCrossEntropyWithProbabilitiesLoss",
Expand Down