【问题标题】:Finding data trendlines with Ruby?用 Ruby 寻找数据趋势线?
【发布时间】:2018-07-20 10:57:18
【问题描述】:

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

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]
...

等等。

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

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

【问题讨论】:

标签: ruby statistics analytics trendline


【解决方案1】:

找到趋势线的数学公式,您可以很容易地定义您的自定义方法。 例如,在这个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}

斜率表示增长:符号表示方向(+ 表示增长,- 表示减少),值表示多快。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    相关资源
    最近更新 更多