This is a Python forum, but what you are asking is not a Python question.  You might find a better source of answers on a scipy specific forum.

But here's my attempt at answers:



On 06/19/2018 08:26 AM, sharan.basa...@gmail.com wrote:
Hi All,

I am working out an exercise on curve_fit function available scipy package.

While I understand in general about curve_fit, I am unable to understand the 
following:

params, params_covariance = optimize.curve_fit(test_func, x_data, y_data,
                                                p0=[2, 2])

Firstly, I don't understand why test_func is passed as an argument to cur_fit

You are trying to fit a curve to some data, right.  The curve_fit procedure needs to know what curve you are trying to fit.  Is it a linear curve, exponential, polynomial or ...?  In this example it's a sine function with parameters for regulating amplitude and frequency.  But it could be any function with any parameters.  To be more precise, test_function is not a single function y=f(x), but a whole family of functions y=f(x; a,b) where a and b define a particular function.

Secondly, I don't understand how curve_fit knows the number of arguments that 
test_func takes.

Part of the dynamic nature of Python is that a function carries with it the number of parameters (as just one among many such properties).  We call it "introspection" when we examine such properties of objects.  The curve_fit function usees such an introspection to find that test_function has two parameters (a and b) defining the family of curves.


Full code is available below for reference:

import numpy as np

# Seed the random number generator for reproducibility
np.random.seed(0)

x_data = np.linspace(-5, 5, num=50)
y_data = 2.9 * np.sin(1.5 * x_data) + np.random.normal(size=50)

# And plot it
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data)

from scipy import optimize

def test_func(x, a, b):
     return a * np.sin(b * x)

params, params_covariance = optimize.curve_fit(test_func, x_data, y_data,
                                                p0=[2, 2])

print(params)

plt.figure(figsize=(6, 4))
plt.scatter(x_data, y_data, label='Data')
plt.plot(x_data, test_func(x_data, params[0], params[1]),
          label='Fitted function')

plt.legend(loc='best')

plt.show()

--
Dr. Gary Herron
Professor of Computer Science
DigiPen Institute of Technology
(425) 895-4418

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to