Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'delegate'
class Series < SimpleDelegator
def self.of(*xs)
new(xs)
end
def mean
@mean ||= sum / size.to_f
end
def variance
@variance ||= reduce(0.0) { |s, x| s + (x - mean) ** 2 } / size.to_f
end
end
class Correlation
def self.score(a, b)
new(a, b).score
end
def initialize(a, b)
@a, @b = a, b
end
def score
((1 / size) * (seq.sum { |(an, bn)| (an - a.mean) * (bn - b.mean) }) / ( Math.sqrt(a.variance * b.variance) )).abs
end
def inspect
"Correlation(score=#{'%0.3f' % score} a=[#{a.join(',')}] b=[#{b.join(',')}])"
end
private
attr_reader :a, :b
def size
a.size.to_f
end
def seq
@seq = a.zip(b)
end
end
s = Series.of(1,2)
puts s.mean
puts s.variance
puts Correlation.new(Series.of(1,1,1,5,1,1,1), Series.of(2,3,2,20,2,2,2)).inspect
puts Correlation.new(Series.of(1,1,1,5,1,1,1), Series.of(1,0,0,0,0,0,0)).inspect
puts Correlation.new(Series.of(1,1,1,5,1,1,1), Series.of(0,0,0,1,0,0,0)).inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.