用于执行线性或非线性最小二乘逼近的Ruby库?

10

是否有一个Ruby库可以让我对一组数据进行线性或非线性最小二乘逼近。

我想要做的是:

  • 给定一系列[x,y]数据点
  • 为该数据生成线性或非线性最小二乘逼近
  • 该库不需要确定它是否需要进行线性或非线性逼近。调用该库的人应该知道他们需要哪种回归方法。

我希望不必尝试将一些C/C++/Java库转换为Ruby以获取此功能,因此我希望有一些现有的Ruby库可供使用。


你尝试过阅读 https://dev59.com/kXRB5IYBdhLWcg3wJkhC 和 https://dev59.com/vm035IYBdhLWcg3wcvmS 以及 https://dev59.com/b1PTa4cB1Zd3GeqPlKY5 吗? - Andrew Grimm
我已经查阅了这些库,只有linalg库表明它可以进行最小二乘逼近,但是当我深入源代码时,我没有找到实现。 - Peter C
在你的问题中提到这可能是个好主意。 - Andrew Grimm
3个回答

8
请尝试使用“statsample”宝石。您可以使用下面提供的示例执行对数、指数、幂或任何其他转换。希望这能帮到您。
require 'statsample'

# Independent Variable
x_data = [Math.exp(1), Math.exp(2), Math.exp(3), Math.exp(4), Math.exp(5)]

# Dependent Variable
y_data = [3, 5, 7, 9, 11]

# Logarithmic Transformation of X data 
# Math.log in Ruby has the base of Euler's number 'e' ~= '2.71828', 
# instead of the base '10'. Just a note.
log_x_data = x_data.map { |x| Math.log(x) }

# Linear Regression using the Logarithmic Transformation
x_vector=log_x_data.to_vector(:scale)
y_vector=y_data.to_vector(:scale)
ds={'x'=>x_vector,'y'=>y_vector}.to_dataset
mlr=Statsample::Regression.multiple(ds,'y')
mlr.summary

# Provides the value of the y-intercept 
#p mlr.constant

# Lists the coefficients of each casual variable. In this case, we have only one--'x'.
#p mlr.coeffs

# The regression output produces the line y = 1 + 2*x, but 
# considering that we transformed x earlier, it really produces
# y = 1 + 2*ln(x).

7
我使用了这个代码片段来计算一些回归。第一个参数是包含x坐标的数组,第二个参数是包含y坐标的数组,最后一个参数是您要查找的多项式的次数。不确定这是否符合您的需求,但希望能有所帮助。

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接