Re: Automate datafitting to a series of parameterized function
- To: mathgroup at smc.vnet.net
- Subject: [mg70303] Re: Automate datafitting to a series of parameterized function
- From: Peter Pein <petsie at dordos.net>
- Date: Thu, 12 Oct 2006 05:37:34 -0400 (EDT)
- References: <egi1h9$j6r$1@smc.vnet.net>
Peng Yu schrieb:
> Suppose I have some data x_i, y_i. Let us generated them by
>
> coef = Table[Random[Real, {-1, 1}], {i, 0, 4}]
> poly = Table[x^n, {n, 0, 4}]
> data = Table[{x, coef.poly}, {x, 0, 1, .01}]
>
> Let us forget how we generated the data. Now, we want to find an
> function to fit the data. The simplest way to do is using Tayler
> series. But the problem is I don't know how many terms I should keep.
> One way I can do is to try for different number of terms. I start by
> only 1 term (0th order).
>
> f[x_, a0_] := a0
> f[x_] := Evaluate@NonlinearFit[data, f[x, a0], {x}, {a0}]
> error = Apply[(f[#1] - #2)^2 &, data, {1}];
> avererror = Apply[Plus, error]/Length[data]
> maxerror = Apply[Max, error]
>
> If the above one doesn't work, I'll try 2 terms (0th and 1st order).
> f[x_, a0_, a1_] := a0 + a1 x
> f[x_] := Evaluate@NonlinearFit[data, f[x, a0, a1], {x}, {a0, a1}];
> error = Apply[(f[#1] - #2)^2 &, data, {1}];
> avererror = Apply[Plus, error]/Length[data]
> maxerror = Apply[Max, error]
>
> I can try even higher orders. But the problem is that ever time I have
> to define the function f[x_,a0_...] and supply the right function and
> parameter list to NonlinearFit. I feel it is especially difficult to
> parameterize the number of parameters to a function.
>
> Can some give some idea on how to do it if it is possible in
> Mathematica? Of cause I could write a python program to generate the
> mathematica code, and call math.exe in the command line mode. But that
> is just to much, I just want to stick with mathematica.
>
> Thanks,
> Peng
>
Hi Peng,
there is no need to
- state all the a_k explicitly in the function call. The approximations can be
built dynamically.
- use NonlinearFit; Fit is sufficient.
In[1]:=
n = 4;
SeedRandom[12]
coef = Table[2*Random[] - 1, {n + 1}]
data = Transpose[{#1, (coef . #1^Range[0, n] & ) /@ #1}]&[0.01*Range[100]];
lpl = ListPlot[data, PlotStyle -> {AbsolutePointSize[4]}]
Out[3]= (* the coefficients *)
{0.465631143384559, 0.2213501334248431, -0.9824888769638274,
0.27138778246826445, 0.7190072574890038}
Out[5]=
Graphics[]
In[6]:=
f[k_] := Fit[data, x^Range[0, k], x]
The errors for k=0..6:
In[7]:=
Chop[Norm/@Table[f[k]/.x->#1&/@First/@data - Last/@data, {k, 0, 6}]]
Out[7]=
{0.6339511113440388, 0.6050342778548943, 0.3273264300746273,
0.034187091387071745, 0, 0, 0}
In[8]:=
DisplayTogether[lpl, Plot[Evaluate[f /@ Range[0, n]], {x, 0, 1},
PlotStyle -> Table[Hue[(1 - j/n)/2], {j, 0, n}]], ImageSize -> {640, 480},
Background -> Black]
Out[8]=
Graphics[]
Peter
P.S.: Have a look at Interpolation too!