Package Scientific :: Package Functions :: Module LeastSquares
[frames] | no frames]

Module LeastSquares

Non-linear least squares fitting

Usage example:

   from Scientific.N import exp

   def f(param, t):
       return param[0]*exp(-param[1]/t)

   data_quantum = [(100, 3.445e+6),(200, 2.744e+7),
                   (300, 2.592e+8),(400, 1.600e+9)]
   data_classical = [(100, 4.999e-8),(200, 5.307e+2),
                     (300, 1.289e+6),(400, 6.559e+7)]

   print leastSquaresFit(f, (1e13,4700), data_classical)

   def f2(param, t):
       return 1e13*exp(-param[0]/t)

   print leastSquaresFit(f2, (3000.,), data_quantum)
Functions
(list, float)
leastSquaresFit(model, parameters, data, max_iterations=None, stopping_limit=0.005)
General non-linear least-squares fit using the Levenberg-Marquardt algorithm and automatic differentiation.
 
polynomialLeastSquaresFit(parameters, data)
Least-squares fit to a polynomial whose order is defined by the number of parameter values.
Function Details

leastSquaresFit(model, parameters, data, max_iterations=None, stopping_limit=0.005)

 

General non-linear least-squares fit using the Levenberg-Marquardt algorithm and automatic differentiation.

Parameters:
  • model (callable) - the function to be fitted. It will be called with two parameters: the first is a tuple containing all fit parameters, and the second is the first element of a data point (see below). The return value must be a number. Since automatic differentiation is used to obtain the derivatives with respect to the parameters, the function may only use the mathematical functions known to the module FirstDerivatives.
  • parameters (tuple of numbers) - a tuple of initial values for the fit parameters
  • data (list) - a list of data points to which the model is to be fitted. Each data point is a tuple of length two or three. Its first element specifies the independent variables of the model. It is passed to the model function as its first parameter, but not used in any other way. The second element of each data point tuple is the number that the return value of the model function is supposed to match as well as possible. The third element (which defaults to 1.) is the statistical variance of the data point, i.e. the inverse of its statistical weight in the fitting procedure.
Returns: (list, float)
a list containing the optimal parameter values and the chi-squared value describing the quality of the fit

polynomialLeastSquaresFit(parameters, data)

 

Least-squares fit to a polynomial whose order is defined by the number of parameter values.

Parameters:
  • parameters (tuple) - a tuple of initial values for the polynomial coefficients
  • data (list) - the data points, as for leastSquaresFit

Note: This could also be done with a linear least squares fit from Scientific.LA