-
Notifications
You must be signed in to change notification settings - Fork 5
/
detector_spec.rb
79 lines (59 loc) · 1.88 KB
/
detector_spec.rb
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
require "spec_helper"
describe Anomaly::Detector do
let(:examples) { [[-1, -2, 0], [0, 0, 0], [1, 2, 0]] }
let(:ad) { Anomaly::Detector.new(examples) }
# mean = [0, 0], std = [1, 2]
it "computes the right probability" do
expect(ad.probability([0, 0])).to eq(0.079577471545947667)
end
it "computes the right mean" do
expect(ad.mean).to eq([0, 0])
end
it "computes the right standard deviation" do
expect(ad.std).to eq([1, 2])
end
it "marshalizes" do
expect { Marshal.dump(ad) }.to_not raise_error
end
context "when standard deviation is 0" do
let(:examples) { [[0, 0], [0, 0]] }
it "returns infinity for mean" do
expect(ad.probability([0])).to eq(1)
end
it "returns 0 for not mean" do
expect(ad.probability([1])).to eq(0)
end
end
context "when examples is an array" do
let(:examples) { [[-1, -2, 0], [0, 0, 0], [1, 2, 0]] }
let(:sample) { [rand, rand] }
it "returns the same probability as an NMatrix" do
prob = ad.probability(sample)
Object.send(:remove_const, :NMatrix)
expect(prob).to eq(Anomaly::Detector.new(examples).probability(sample))
end
end
context "when lots of samples" do
let(:examples) { m.times.map { [0, 0] } }
let(:m) { rand(100) + 1 }
it { expect(ad.trained?).to be_truthy }
end
context "when no samples" do
let(:examples) { nil }
it { expect(ad.trained?).to be_falsey }
end
context "when pdf is greater than 1" do
let(:examples) { 100.times.map { [0, 0] }.push([1, 0]) }
it { expect(ad.probability([0])).to eq(1) }
end
context "when only anomalies" do
let(:examples) { [[0, 1]] }
it "raises error" do
expect { ad }.to raise_error RuntimeError, "Must have at least one non-anomaly"
end
end
context "when only one non-anomaly" do
let(:examples) { [[0, 0]] }
it { expect(ad.eps).to eq(1e-1) }
end
end