-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAnomalyDetectionUtil.cs
126 lines (107 loc) · 3.08 KB
/
AnomalyDetectionUtil.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
using System;
using System.Collections.Generic;
namespace DesktopApp
{
//Line class
public class Line
{
private readonly float _a;
private readonly float _b;
public Line()
{
_a = 0;
_b = 0;
}
public Line(float a, float b)
{
this._a = a;
this._b = b;
}
public float F(float x)
{
return _a * x + _b;
}
}
//Point class
public class Point
{
public readonly float X;
public readonly float Y;
public Point(float x, float y)
{
X = x;
Y = y;
}
}
//AnomalyDetectionUtil library
public static class AnomalyDetectionUtil
{
//average of x
private static float Avg(IReadOnlyList<float> x)
{
float sum = 0;
for (var i = 0; i < x.Count; sum += x[i], i++)
{
}
return sum / x.Count;
}
// returns the variance of X and Y
private static float Var(IReadOnlyList<float> x)
{
var av = Avg(x);
float sum = 0;
foreach (var t in x)
{
sum += t * t;
}
return sum / x.Count - av * av;
}
// returns the covariance of X and Y
private static float Cov(IReadOnlyList<float> x, IReadOnlyList<float> y)
{
var size = Math.Min(y.Count, x.Count); //same as y.Length
float sum = 0;
for (var i = 0; i < size; i++)
{
sum += x[i] * y[i];
}
sum /= size;
return sum - Avg(x) * Avg(y);
}
// returns the Pearson correlation coefficient of X and Y
public static float Pearson(float[] x, float[] y)
{
var r = Cov(x, y) / (float) (Math.Sqrt(Var(x)) * Math.Sqrt(Var(y)));
return float.IsNaN(r) ? 0 : r;
}
// performs a linear regression and returns the line equation
public static Line LinearReg(Point[] points)
{
var size = points.Length;
var x = new float[size];
var y = new float[size];
for (var i = 0; i < size; i++)
{
x[i] = points[i].X;
y[i] = points[i].Y;
}
var a = Cov(x, y) / Var(x);
var b = Avg(y) - a * (Avg(x));
return new Line(a, b);
}
// returns the deviation between point p and the line equation of the points
public static float Dev(Point p, Point[] points)
{
var l = LinearReg(points);
return Dev(p, l);
}
// returns the deviation between point p and the line
private static float Dev(Point p, Line l)
{
var x = p.Y - l.F(p.X);
if (x < 0)
x *= -1;
return x;
}
}
}