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

Commit 290af7b

Browse files
Shashi456rxwei
authored andcommitted
Add logarithm-cosine loss (#227)
1 parent c108a10 commit 290af7b

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

Sources/TensorFlow/Loss.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,26 @@ public func categoricalHingeLoss<Scalar: TensorFlowFloatingPoint>(
128128
return max(Tensor(0), negative - positive + Tensor(1))
129129
}
130130

131+
// Helper function for `losCoshLoss(predicted:expected:)`.
132+
@differentiable
133+
fileprivate func logCosh<Scalar: TensorFlowFloatingPoint>(
134+
_ x: Tensor<Scalar>
135+
) -> Tensor<Scalar> {
136+
x + softplus(Tensor(-2) * x) - log(Tensor(2))
137+
}
138+
139+
/// Returns the logarithm of the hyperbolic cosine of the error between predictions and expectations.
140+
///
141+
/// - Parameters:
142+
/// - predicted: Predicted outputs from a neural network.
143+
/// - expected: Expected values, i.e. targets, that correspond to the correct output.
144+
@differentiable(wrt: predicted)
145+
public func logCoshLoss<Scalar: TensorFlowFloatingPoint>(
146+
predicted: Tensor<Scalar>, expected: Tensor<Scalar>
147+
) -> Tensor<Scalar> {
148+
(logCosh(predicted - expected)).mean()
149+
}
150+
131151
/// Returns the Poisson loss between predictions and expectations.
132152
///
133153
/// - Parameters:

Tests/TensorFlowTests/LossTests.swift

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,14 @@ final class LossTests: XCTestCase {
121121
assertElementsEqual(expected: Tensor(expectedLoss), actual: loss)
122122
}
123123

124+
func testLogCoshLoss() {
125+
let predicted = Tensor<Float>([0.2, 0.3, 0.4])
126+
let expected = Tensor<Float>([1.0, 4.0, 3.0])
127+
let loss = logCoshLoss(predicted: predicted, expected: expected)
128+
let expectedLoss: Float = 1.7368573
129+
assertElementsEqual(expected: Tensor(expectedLoss), actual: loss)
130+
}
131+
124132
func testPoissonLoss() {
125133
let predicted = Tensor<Float>([0.1, 0.2, 0.3])
126134
let expected = Tensor<Float>([1, 2, 3])
@@ -238,7 +246,8 @@ final class LossTests: XCTestCase {
238246
("testKullbackLeiblerDivergence", testKullbackLeiblerDivergence),
239247
("testCategoricalHingeLoss", testCategoricalHingeLoss),
240248
("testSquaredHingeLoss", testSquaredHingeLoss),
241-
("testPoissonLoss", testPoissonLoss),
249+
("testPoissonLoss",testPoissonLoss),
250+
("testLogCoshLoss", testLogCoshLoss),
242251
("testSoftmaxCrossEntropyWithProbabilitiesLoss",
243252
testSoftmaxCrossEntropyWithProbabilitiesLoss),
244253
("testSoftmaxCrossEntropyWithProbabilitiesGrad",

0 commit comments

Comments
 (0)