如何在 PHP 中计算趋势线?
因此,我已经阅读了计算图表趋势线的两个相关问题,但我仍然迷失方向。
我有一个 xy 坐标数组,我想用 PHP 提出另一个 xy 坐标数组(可以更少的坐标)来表示对数趋势线。
我将这些数组传递给 JavaScript 以在客户端绘制图表。
So I've read the two related questions for calculating a trend line for a graph, but I'm still lost.
I have an array of xy coordinates, and I want to come up with another array of xy coordinates (can be fewer coordinates) that represent a logarithmic trend line using PHP.
I'm passing these arrays to javascript to plot graphs on the client side.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对数最小二乘
由于我们可以通过取
x
值的log
将对数函数转换为直线,因此我们可以执行 线性最小二乘曲线拟合。事实上,我们已经完成了这项工作,并且在 Math World 中提供了解决方案。简而言之,我们得到的
$X
和$Y
值来自y = a + b * log(x)
等分布。最小二乘法将给出一些值aFit
和bFit
,以最小化参数曲线到给定数据点的距离。这是 PHP 中的示例实现:
首先,我将生成一些具有由
$a
和$b
给出的已知底层分布的随机数据。以下是如何使用给出的方程来估计
$a
和$b
。然后,您可以根据需要为 Javascript 生成密集的点:
在本例中,代码估计
bFit = 5.17
和aFit = 9.7
,仅对于 < code>50 数据点。对于下面评论中给出的示例数据,对数函数不太适合。
最小二乘解为
y = -514.734835478 + 2180.51562281 * log(x)
本质上是该域中的一条线。Logarithmic Least Squares
Since we can convert a logarithmic function into a line by taking the
log
of thex
values, we can perform a linear least squares curve fitting. In fact, the work has been done for us and a solution is presented at Math World.In brief, we're given
$X
and$Y
values that are from a distribution likey = a + b * log(x)
. The least squares method will give some valuesaFit
andbFit
that minimize the distance from the parametric curve to the data points given.Here is an example implementation in PHP:
First I'll generate some random data with known underlying distribution given by
$a
and$b
Now, here's how to use the equations given to estimate
$a
and$b
.You may then generate points for your Javascript as densely as you like:
In this case, the code estimates
bFit = 5.17
andaFit = 9.7
, which is quite close for only50
data points.For the example data given in the comment below, a logarithmic function does not fit well.
The least squares solution is
y = -514.734835478 + 2180.51562281 * log(x)
which is essentially a line in this domain.我建议使用库: http://www.drque.net/Projects/PolynomialRegression/
由 Composer 提供: https://packagist.org/packages/dr-que/polynomial-regression 。
I would recommend using library: http://www.drque.net/Projects/PolynomialRegression/
Available by Composer: https://packagist.org/packages/dr-que/polynomial-regression.
如果有人在使用 create_function 时遇到问题,以下是我编辑它的方法。 (虽然我没有使用日志,所以我确实把它们去掉了。)
我还减少了计算次数并添加了 R2。到目前为止似乎有效。
In case anyone is having problems with the create_function, here is how I edited it. (Though I wasn't using logs, so I did take those out.)
I also reduced the number of calculations and added an R2. It seems to work so far.