w3resource

Fit a curve to sample data using NumPy and SciPy's curve_fit

NumPy: Integration with SciPy Exercise-6 with Solution

Write a NumPy program to create a set of sample data and fit a curve using SciPy's curve_fit function.

Sample Solution:

Python Code:

# Import necessary libraries
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

# Create a set of sample data using NumPy
np.random.seed(0)  # For reproducibility
x = np.linspace(0, 10, 100)
y = 2.5 * np.sin(1.5 * x) + np.random.normal(size=x.size)

# Define the model function to be fitted
def model_func(x, a, b):
    return a * np.sin(b * x)

# Use SciPy's curve_fit function to fit the model to the data
params, covariance = curve_fit(model_func, x, y)

# Extract the fitted parameters
a_fit, b_fit = params

# Generate y values using the fitted parameters
y_fit = model_func(x, a_fit, b_fit)

# Plot the original data and the fitted curve
plt.scatter(x, y, label='Sample Data')
plt.plot(x, y_fit, label='Fitted Curve', color='red')
plt.legend()
plt.show()

Output:

Fit a curve to sample data using NumPy and SciPy's curve_fit

Explanation:

  • Import necessary libraries:
    • Import NumPy, SciPy's curve_fit function, and Matplotlib for plotting.
  • Create a set of sample data using NumPy:
    • Generate x values evenly spaced between 0 and 10, and corresponding y values using a sine function with added noise.
  • Define the model function to be fitted:
    • Create a sine function model with parameters a and b.
  • Use SciPy's curve_fit function to fit the model to the data:
    • Fit the model function to the data to determine the best-fit parameters.
  • Extract the fitted parameters:
    • Retrieve the parameters a and b from the fitting process.
  • Generate y values using the fitted parameters:
    • Use the fitted parameters to generate the y values.
  • Plot the original data and the fitted curve:
    • Use Matplotlib to visualize the sample data and the fitted curve.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Filter Time Series data using NumPy and SciPy Signal processing.
Next: Perform Hypothesis testing with NumPy and SciPy's Stats module.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/fit-a-curve-to-sample-data-using-numpy-and-scipys-curve_fit.php