Created
September 18, 2019 19:42
-
-
Save olivernn/d391654b68f9ad0b145590a21c0714ed to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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