ruby - 用 Ruby 拟合幂律
问题描述
我有这些数据,需要像在 Excel 中那样执行“幂律曲线拟合”。
我曾尝试使用 Ruby/GSl,但只有“指数拟合”。你知道图书馆或其他适合功率曲线的东西吗?
文档:https ://blackwinter.github.io/rb-gsl/rdoc/fit_rdoc.html#label-Exponential+fitting
# Fitting
a2, b2, = Fit.linear(x, Sf::log(y))
x2 = Vector.linspace(0, 5, 20)
A = Sf::exp(a2)
printf("Expect: a = %f, b = %f\n", a, b)
printf("Result: a = %f, b = %f\n", A, b2)
graph([x, y], [x2, A*Sf::exp(b2*x2)], "-C -g 3 -S 4")
解决方案
我解决了这个
x = [ [1, 2, 3, 4], [1,1,1,1] ]
y = [3, 5, 7, 9]
# Y = Cx^b
# Log10 Y = Log C + b * Log X
def regression_coefficients y, x
y = Matrix.column_vector y.map { |i| i.to_f }
x = Matrix.columns x.map { |xi| xi.map { |i| i.to_f }}
(x.t * x).inverse * x.t * y
end
推荐阅读
- kubernetes - 也无法在具有最新 kubernetes 版本的 gke 集群中使用高级行为配置
- python - 在 sqlalchemy 中使用 sum 和 case 时出错
- flutter - 如何在底部和所有侧面创建带有盒子阴影的容器
- github - 在 Github Desktop 中意外删除了存储 - 不知道如何取回它
- firebase - Flutter 如何将多个身份验证提供者链接到一个 Firebase 帐户?
- javascript - 尝试在 `emcc -s ONLY_MY_CODE` 时设置不存在的设置
- pandas - 遍历两个 Pandas Dataframes + 创建新列
- jestjs - 使用 Jest 模拟 Fetch API 中的问题
- apache-camel - 如何在骆驼中有一次性路线?
- python-3.x - 通过在 python 中最小化远程桌面连接,屏幕捕获失败