Ruby中的多项式回归函数问题

时间:2017-05-11 13:43:22

标签: ruby math matrix regression

我很难找到一个好的Ruby库来进行回归,所以我已经为多项式回归编写了自己的函数。我偶尔会得到一些看起来有些正确的曲线,但大部分时间曲线都是偏离的。

def self.polynomial_regression(x, y, degree, options = {})
  x_data = x.map { |xi| (0..degree).map { |pow| (xi**pow).to_f } }

  mx = Matrix[*x_data]
  my = Matrix.column_vector(y)

  poly = ((mx.t * mx).inv * mx.t * my).transpose.to_a[0]

  result = {}
  result[:fn] = Proc.new do |x|
    return nil if x.nil?
    if x.kind_of?(Array)
      x.collect { |v|
        if v.nil?
          nil
        else
          poly.each_with_index.map{ |p, i|
            p*(v**i)
          }.reduce(:+)
        end
      }
    else
      poly.each_with_index.map{ |p, i|
        p*(x**i)
      }.reduce(:+)
    end
  end

  result
end

这里出现了数学错误,我不知道它在哪里。

poly变量包含回归系数。然后我使用它来生成一个函数,使用poly和输入x值,其中我乘以每个系数px值,并将其提升到正确的指数{{ 1}}。

i

我不是任何统计专家,但我认为这是正确的数学。我的逻辑中是否存在错误,或者我在实现中出错?

1 个答案:

答案 0 :(得分:0)

   def regress x, y, degree
        x_data = x.map { |xi| (0..degree).map { |pow| (xi**pow).to_r } }
       
        mx = Matrix[*x_data]
        my = Matrix.column_vector(y)
       
        ((mx.t * mx).inv * mx.t * my).transpose.to_a[0].map(&:to_f)
      end

方法

p regress([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
          [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321],
          2)

输出

[1.0、2.0、3.0]