Class: Regress

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-regress.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(a, b = nil) ⇒ Regress

Create a Regress object from two vectors a and b. Note that a and b must be of the same length.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/ruby-regress.rb', line 5

def initialize(a,b=nil)
  if b.nil?
    # Don't do regression if we're only given one item
  else
    raise "Regress#initialize expects two vectors of equal length (given vectors of lengths #{a.size}, #{b.size})." if a.size != b.size
    
    sa,sb = *[a,b].map { |d| Regress.sum(d) }
    sa2,sb2 = *[a,b].map { |d| Regress.sum(Regress.square(d)) }
    sab = Regress.multiply(a,b)
    n = a.size
    
    @r = (n * sab - sa * sb) / (( (n * sa2 - sa**2) * (n * sb2 - sb**2) ) ** 0.5)
    @r = 0.0 if @r.nan?
  end
end

Instance Attribute Details

#interceptObject (readonly)

Returns the value of attribute intercept.



2
3
4
# File 'lib/ruby-regress.rb', line 2

def intercept
  @intercept
end

#rObject (readonly)

Returns the value of attribute r.



2
3
4
# File 'lib/ruby-regress.rb', line 2

def r
  @r
end

#slopeObject (readonly)

Returns the value of attribute slope.



2
3
4
# File 'lib/ruby-regress.rb', line 2

def slope
  @slope
end

Class Method Details

.max(vector) ⇒ Object



37
38
39
# File 'lib/ruby-regress.rb', line 37

def Regress.max(vector)
  vector.sort.pop
end

.mean(vector) ⇒ Object



41
42
43
# File 'lib/ruby-regress.rb', line 41

def Regress.mean(vector)
  Regress.sum(vector) / vector.size.to_f
end

.min(vector) ⇒ Object



33
34
35
# File 'lib/ruby-regress.rb', line 33

def Regress.min(vector)
  vector.sort.shift
end

.multiply(a, b) ⇒ Object



29
30
31
# File 'lib/ruby-regress.rb', line 29

def Regress.multiply(a,b)
  (0..a.size-1).inject(0) { |s,i| s += a[i] * b[i] }
end

.square(vector) ⇒ Object



25
26
27
# File 'lib/ruby-regress.rb', line 25

def Regress.square(vector)
  vector.map { |x| x**2 }
end

.standard_deviation(vector) ⇒ Object



45
46
47
48
# File 'lib/ruby-regress.rb', line 45

def Regress.standard_deviation(vector)
  mean = Regress.mean(vector)
  (vector.collect { |x| (x-mean)**2 }.inject(0) { |s,x| s += x } / (vector.size.to_f-1)) ** 0.5
end

.sum(vector) ⇒ Object



21
22
23
# File 'lib/ruby-regress.rb', line 21

def Regress.sum(vector)
  vector.inject(0) { |s,x| s += x }
end