Non-linear Least Squares Fitting (2-dimensional) in Python
<p>I was wondering what the correct approach to fitting datapoints to a non-linear function should be in python.</p>

<p>I am trying to fit a series of data-points</p>

<pre><code>t = [0., 0.5, 1., 1.5, ...., 4.]
y = [6.3, 4.5,.................]
</code></pre>

<p>using the following model function</p>

<pre><code>f(t, x) = x1*e^(x2*t)
</code></pre>

<p>I was mainly wondering which library routine is appropriate for this problem and how it should be setup. I tried using the following with unsuccessful results:</p>

<pre><code>t_data = np.array([0.5, 1.0, 1.5, 2.0,........])
y_data = np.array([6.8, 3., 1.5, 0.75........])

def func_nl_lsq(x, t, y):
    return [x[0]*np.exp(x[1]*t)] -  y

popt, pcov = scipy.optimize.curve_fit(func_nl_lsq, t_data, y_data)
</code></pre>

<p>I know it's unsuccessful because I am able to solve the "equivalent" linear least squares problem (simply obtained by taking the log of the model function) and its answer doesn't even come close to the one I am getting by doing the above.</p>

<p>Thank you</p>

<p><code>scipy.otimize.curve_fit</code> can be used to fit the data. I think you just don't use it properly. I assume you have a given <code>t</code> and <code>y</code> and try to fit a function of the form <code>x1*exp(x2*t) = y</code>.</p>

<p>You need</p>

<pre><code>ydata = f(xdata, *params) + eps
</code></pre>

<p>This means your function is not defined properly. Your function should look like probably look like </p>

<pre><code>def func_nl_lsq(t, x1, x2):
    return x1*np.exp(x2*t)
</code></pre>

<p>depending what you really want to fit. Here x1 and x2 are your fitting parameter. It is also possible to do</p>

<pre><code>def func_nl_lsq(t, x):
    return x[0]*np.exp(x[1]*t)
</code></pre>

<p>but you likely need to provide an initial guess p0.</p>

python numpy optimization scipy linear-algebra