Polynomial regression: Difference between revisions

<code>
m (Taking "Example" off the TOC)
(<code>)
Line 14:
 
=={{header|Ada}}==
<code ada>
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
 
Line 27:
return Solve (A * Transpose (A), A * Y);
end Fit;
</adacode>
The function Fit implements least squares approximation of a function defined in the points as specified by the arrays ''x''<sub>''i''</sub> and ''y''<sub>''i''</sub>. The basis &phi;<sub>''j''</sub> is ''x''<sup>''j''</sup>, ''j''=0,1,..,''N''. The implementation is straightforward. First the plane matrix A is created. A<sub>ji</sub>=&phi;<sub>''j''</sub>(''x''<sub>''i''</sub>). Then the linear problem AA<sup>''T''</sup>''c''=A''y'' is solved. The result ''c''<sub>''j''</sub> are the coefficients. Constraint_Error is propagated when dimensions of X and Y differ or else when the problem is ill-defined.
===Example===
<code ada>
with Fit;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
Line 46:
Put (C (2), Aft => 3, Exp => 0);
end Fitting;
</adacode>
Sample output:
<pre>
Line 155:
 
{{libheader|numpy}}
<code python>
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> yx = [10, 61, 172, 343, 574, 865, 121 6, 162 7, 209 8, 262 9, 32110]
>>> xy = [01, 1 6, 217, 334, 457, 586, 6121, 7162, 8209, 9262, 10321]
>>> coeffs = numpy.polyfit(x,y,deg=2)
>>> coeffs = numpy.polyfit(x,y,deg=2)
>>> coeffs
array([ 3., 2., 1.])
</code>
Substitute back received coefficients.
<code python>
>>> yf = numpy.polyval(numpy.poly1d(coeffs), x)
>>> yf
array([ 1., 6., 17., 34., 57., 86., 121., 162., 209., 262., 321.])
</code>
Find max absolute error.
<code python>
>>> '%.1g' % max(y-yf)
'1e-013'
</code>
 
===Example===
For input arrays `x' and `y':
<code python>
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> yx = [2.70, 2.81, 31.42, 38.13, 58.04, 76.25, 100.56, 130.07, 149.38, 180.09]
>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
</code>
 
<code python>
>>> p = numpy.poly1d(numpy.polyfit(x, y, deg=2), variable='N')
>>> coeffsp = numpy.poly1d(numpy.polyfit(x, y, deg=2), variable='N')
>>> print p
2
1.085 N + 10.36 N - 0.6164 2
1.085 N + 10.36 N - 0.6164
</code>
Thus we confirm once more that for already sorted sequences the considered quick sort implementation has quadratic dependence on sequence length (see [[Query Performance|'''Example''' section for Python language on ''Query Performance'' page]]).
973

edits