代码之家  ›  专栏  ›  技术社区  ›  The Whiz of Oz

用Ruby查找数据趋势线?

  •  0
  • The Whiz of Oz  · 技术社区  · 8 年前

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

    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有大量的解决方案和libs,而ruby只有一个gem( trendline )里面没有代码。在我开始学习如何使用数学之前,也许有人有一个可行的解决方案?

    1 回复  |  直到 8 年前
        1
  •  2
  •   iGian    8 年前

    找到趋势线的数学公式,可以很容易地定义自定义方法。 例如,遵循这一点 https://math.stackexchange.com/questions/204020/what-is-the-equation-used-to-calculate-a-linear-trendline ,我猴子修补了数组类。

    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}
    

    坡度表示增长:符号表示方向(+is growing,-is decreasing),值表示速度。

    推荐文章