Untitled

 avatar
unknown
plain_text
a year ago
1.1 kB
3
Indexable
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

# Exponential function
def exponential_func(x, a, b):
    return a * np.exp(b * x)

# Generate sample data
np.random.seed(42)
x_data = np.linspace(0, 5, 50)  # Replace with your desired x values
y_true = 2 * np.exp(0.5 * x_data) + np.random.normal(0, 0.5, len(x_data))  # Example exponential data with noise

# Fit the exponential function to the data
initial_guess = [1, 1]  # Initial guess for the parameters (a, b)
params, covariance = curve_fit(exponential_func, x_data, y_true, p0=initial_guess)

# Extract fitted parameters
a_fit, b_fit = params

# Generate fitted data using the parameters
y_fit = exponential_func(x_data, a_fit, b_fit)

# Plot the original data and the fitted curve
plt.scatter(x_data, y_true, label='Original Data')
plt.plot(x_data, y_fit, color='red', label=f'Exponential Fit: y = {a_fit:.2f} * e^({b_fit:.2f} * x)')
plt.legend()
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Exponential Regression Example')
plt.show()
Leave a Comment