Untitled

unknown
plain_text
2 months ago
1.5 kB
0
Indexable
Never
```import numpy as np
from scipy.optimize import curve_fit
from sklearn.metrics import mean_squared_error, r2_score
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)

# Calculate accuracy metrics
mse = mean_squared_error(y_true, y_fit)
r2 = r2_score(y_true, y_fit)

print(f'Mean Squared Error (MSE): {mse:.4f}')
print(f'R-squared (R2): {r2:.4f}')

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

# Make a prediction for a new value
new_x_value = 6.0  # Replace with the desired new x value
predicted_y = exponential_func(new_x_value, a_fit, b_fit)
print(f'Prediction for x = {new_x_value}: {predicted_y:.4f}')
```