curve_fit in scipy

Sharan Basappa sharan.basappa at gmail.com
Tue Jun 19 11:26:13 EDT 2018


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
Secondly, I don't understand how curve_fit knows the number of arguments that test_func takes.

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()



More information about the Python-list mailing list