I’m working on a project that does some graphing, I and needed to do a linear best fit. A quick google search didn’t find the ruby code snippet I was looking for, so I converted one from PHP. ( Original nasty looking quasi-OO PHP source ) Sorry, no unit tests :)


class LinearRegression
  attr_accessor :slope, :offset

  def initialize dx, dy=nil
    @size = dx.size
    dy,dx = dx,axis() unless dy  # make 2D if given 1D
    raise "arguments not same length!" unless @size == dy.size
    sxx = sxy = sx = sy = 0
    dx.zip(dy).each do |x,y|
      sxy += x*y
      sxx += x*x
      sx  += x
      sy  += y
    end
    @slope = ( @size * sxy - sx*sy ) / ( @size * sxx - sx * sx )
    @offset = (sy - @slope*sx) / @size
  end

  def fit
    return axis.map{|data| predict(data) }
  end

  def predict( x )
    y = @slope * x + @offset
  end

  def axis
    (0...@size).to_a
  end
end

UPDATE: a few people have asked for usage instructions…

For a basic graph, just pass an array to the constructor.


lr = LinearRegression.new( [ 5,1,3,7,10,3,5 ] )
fitted_array = lr.fit
puts "The slope is #{lr.slope}" 

The second argument to the constructor (y-axis) is implied as [0,1,2,3,4,5,6,7] (starting with zero, incrementing by 1) You can pass it a different array for this second argument if you need to.

Sorry, comments are closed for this article.