Skip to content

Commit

Permalink
Added api for mean and standard deviation
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrew Kane committed Feb 28, 2012
1 parent aff716d commit 3ba5a6e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
9 changes: 5 additions & 4 deletions lib/anomaly/detector.rb
@@ -1,5 +1,6 @@
module Anomaly
class Detector
attr_reader :mean, :std
attr_accessor :eps

def initialize(examples = nil, opts = {})
Expand Down Expand Up @@ -45,8 +46,8 @@ def train(examples, opts = {})
else
# Default to Array, since built-in Matrix does not give us a big performance advantage.
cols = @n.times.map{|i| training_examples.map{|r| r[i]}}
@mean = cols.map{|c| mean(c)}
@std = cols.each_with_index.map{|c,i| std(c, @mean[i])}
@mean = cols.map{|c| alt_mean(c)}
@std = cols.each_with_index.map{|c,i| alt_std(c, @mean[i])}
end
@std.map!{|std| (std == 0 or std.nan?) ? Float::MIN : std}

Expand Down Expand Up @@ -120,11 +121,11 @@ def f1_score(tp, fp, fn)

# Not used for NArray

def mean(x)
def alt_mean(x)
x.inject(0.0){|a, i| a + i}/x.size
end

def std(x, mean)
def alt_std(x, mean)
Math.sqrt(x.inject(0.0){|a, i| a + (i - mean) ** 2}/(x.size - 1))
end

Expand Down
8 changes: 8 additions & 0 deletions spec/anomaly/detector_spec.rb
Expand Up @@ -9,6 +9,14 @@
ad.probability([0,0]).should == 0.079577471545947667
end

it "computes the right mean" do
ad.mean.should == [0,0]
end

it "computes the right standard deviation" do
ad.std.should == [1,2]
end

it "marshalizes" do
expect{ Marshal.dump(ad) }.to_not raise_error
end
Expand Down

0 comments on commit 3ba5a6e

Please sign in to comment.