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

Adding Squared Hinge Loss #187

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

@differentiable(wrt: predicted)
public func squaredHingeLoss<Scalar: TensorFlowFloatingPoint>(
predicted: Tensor<Scalar>, expected: Tensor<Scalar>
) -> Tensor<Scalar> {
return (max(Tensor(1) - expected * predicted, Tensor(0))).squared().mean()
}

/// Returns the 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 @@ -68,6 +68,14 @@ final class LossTests: XCTestCase {
assertElementsEqual(expected: Tensor(expectedLoss), actual: loss)
}

func testSquaredHingeLoss() {
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 = squaredHingeLoss(predicted: predicted, expected: expected)
let expectedLoss: Float = 0.03125
assertElementsEqual(expected: Tensor(expectedLoss), actual: loss)
}

func testCategoricalHingeLoss() {
let predicted = Tensor<Float>([3, 4 ,5])
let expected = Tensor<Float>([0.3, 0.4, 0.3])
Expand Down Expand Up @@ -171,6 +179,7 @@ final class LossTests: XCTestCase {
("testMeanSquaredErrorGrad", testMeanSquaredErrorGrad),
("testHingeLoss", testHingeLoss),
("testCategoricalHingeLoss", testCategoricalHingeLoss),
("testSquaredHingeLoss", testSquaredHingeLoss),
("testSoftmaxCrossEntropyWithProbabilitiesLoss",
testSoftmaxCrossEntropyWithProbabilitiesLoss),
("testSoftmaxCrossEntropyWithProbabilitiesGrad",
Expand Down