使用 Ruby 查找数据趋势线?

The*_* Oz 1 ruby statistics analytics trendline

我有一个包含来自我的站点的用户会话编号的数据集,如下所示:

page_1 = [4,2,4,1,2,6,3,2,1,6,2,7,0,0,0]
page_2 = [6,3,2,3,5,7,9,3,1,6,1,6,2,7,8]
...
Run Code Online (Sandbox Code Playgroud)

等等。

我想知道页面在增长方面是否具有正趋势线或负趋势线,但是我也想获得增长/下降超过某个阈值的页面。

Python 为此类任务提供了大量解决方案和库,但 Ruby 只有一个 gem(趋势线),其中没有代码。在我开始学习如何使用数学来做到这一点之前,也许有人有一个可行的解决方案?

iGi*_*ian 5

找到趋势线的数学公式,您可以非常轻松地定义自定义方法。例如,按照这个https://math.stackexchange.com/questions/204020/what-is-the-equation-used-to-calculate-a-linear-trendline,我猴子修补了 Array 类。

class Array

  def trend_line
    points = map.with_index { |y, x| [x+1, y] }
    n = points.size
    summation_xy = points.map{ |e| e[0]*e[1] }.inject(&:+)
    summation_x = points.map{ |e| e[0] }.inject(&:+)
    summation_y = points.map{ |e| e[1] }.inject(&:+)
    summation_x2 = points.map{ |e| e[0]**2 }.inject(&:+)
    slope = ( n * summation_xy - summation_x * summation_y ) / ( n * summation_x2 - summation_x**2 ).to_f
    offset = ( summation_y - slope * summation_x ) / n.to_f
    {slope: slope, offset: offset}
  end

end

p page_1.trend_line #=> {:slope=>-0.1357142857142857, :offset=>3.7523809523809524}
p page_2.trend_line #=> {:slope=>0.1, :offset=>3.8}
Run Code Online (Sandbox Code Playgroud)

斜率为您提供增长:符号表示方向(+ 正在增长,- 正在下降),值表示多快。