使用 Ruby 查找数据趋势线?
Finding data trendlines with Ruby?
我有一个数据集,其中包含我网站上的用户会话数,如下所示:
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]
...
等等。
我想了解该网页在增长方面是否具有正趋势线或负趋势线,但我还想获得 growing/falling 超出特定阈值的网页。
Python 有大量针对此类任务的解决方案和库,但 Ruby 只有一个 gem (trendline) 没有代码.在我开始学习如何使用数学来做到这一点之前,也许有人有可行的解决方案?
找到趋势线的数学公式,您可以很容易地定义您的自定义方法。
例如,在 https://math.stackexchange.com/questions/204020/what-is-the-equation-used-to-calculate-a-linear-trendline 之后,我猴子修补了数组 class.
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}
斜率给你增长:符号表示方向(+是增长,-是下降),值表示多快。
我有一个数据集,其中包含我网站上的用户会话数,如下所示:
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]
...
等等。
我想了解该网页在增长方面是否具有正趋势线或负趋势线,但我还想获得 growing/falling 超出特定阈值的网页。
Python 有大量针对此类任务的解决方案和库,但 Ruby 只有一个 gem (trendline) 没有代码.在我开始学习如何使用数学来做到这一点之前,也许有人有可行的解决方案?
找到趋势线的数学公式,您可以很容易地定义您的自定义方法。 例如,在 https://math.stackexchange.com/questions/204020/what-is-the-equation-used-to-calculate-a-linear-trendline 之后,我猴子修补了数组 class.
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}
斜率给你增长:符号表示方向(+是增长,-是下降),值表示多快。