-
Notifications
You must be signed in to change notification settings - Fork 0
/
LossFunctions.cs
85 lines (67 loc) · 2.56 KB
/
LossFunctions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Linq;
namespace SimpleNeuralNetwork
{
public static class LossFunctions
{
#region Regression losses
public static double MeanAbsoluteError(this double[] guess, double[] expected)
{
double result = 0;
for (int i = 0; i < expected.Length; i++)
result += Math.Abs(expected[i] - guess[i]);
return result / expected.Length;
}
public static double RootMeanSquaredError(this double[] guess, double[] expected)
{
double result = 0;
for (int i = 0; i < expected.Length; i++)
result += Math.Pow(expected[i] - guess[i], 2);
return Math.Sqrt(result) / expected.Length;
}
public static double MeanSquaredError(this double[] guess, double[] expected)
{
double result = 0;
for (int i = 0; i < expected.Length; i++)
result += Math.Pow(expected[i] - guess[i], 2);
return result / (2 * expected.Length);
}
public static double HuberLoss(this double[] guess, double[] expected, double delta = 5)
{
double result = 0;
for (int i = 0; i < expected.Length; i++)
{
var diff = expected[i] - guess[i];
if (Math.Abs(diff) <= delta)
result += 0.5 * Math.Pow(diff, 2);
else
result += delta * diff - 0.5 * Math.Pow(delta, 2);
}
return result / expected.Length;
}
public static double LogCoshLoss(this double[] guess, double[] expected)
{
double result = 0;
for (int i = 0; i < expected.Length; i++)
result += Math.Log(Math.Cosh(expected[i] - guess[i]));
return result / expected.Length;
}
#endregion
#region Classification losses
public static double[] CrossEntropyLoss(this double[] guess, double[] expected)
{
// TODO: Find why this is wrong
// expected[i] = - expected[i] * Math.Log(1e-15 + guess[i]);
for (int i = 0; i < expected.Length; i++)
expected[i] = - Math.Log(expected[i] == 1 ? guess[i] : 1 - guess[i]);
return expected;
}
public static double[] SimpleLoss(this double[] guess, double[] expected)
{
for (int i = 0; i < expected.Length; i++)
expected[i] = expected[i] - guess[i];
return expected;
}
#endregion
}
}