Untitled
unknown
plain_text
a year ago
1.6 kB
5
Indexable
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 sparse sample data np.random.seed(42) x_data_sparse = np.linspace(0, 5, 10) # Reduce the number of data points y_true_sparse = 2 * np.exp(0.5 * x_data_sparse) + np.random.normal(0, 0.5, len(x_data_sparse)) # Example exponential data with noise # Fit the exponential function to the sparse data initial_guess = [1, 1] # Initial guess for the parameters (a, b) params_sparse, covariance_sparse = curve_fit(exponential_func, x_data_sparse, y_true_sparse, p0=initial_guess) # Extract fitted parameters a_fit_sparse, b_fit_sparse = params_sparse # Generate fitted data using the parameters y_fit_sparse = exponential_func(x_data_sparse, a_fit_sparse, b_fit_sparse) # Calculate accuracy metrics for sparse data mse_sparse = mean_squared_error(y_true_sparse, y_fit_sparse) r2_sparse = r2_score(y_true_sparse, y_fit_sparse) print(f'Mean Squared Error (MSE) for Sparse Data: {mse_sparse:.4f}') print(f'R-squared (R2) for Sparse Data: {r2_sparse:.4f}') # Plot the sparse original data and the fitted curve plt.scatter(x_data_sparse, y_true_sparse, label='Sparse Original Data') plt.plot(x_data_sparse, y_fit_sparse, color='red', label=f'Sparse Exponential Fit: y = {a_fit_sparse:.2f} * e^({b_fit_sparse:.2f} * x)') plt.legend() plt.xlabel('X') plt.ylabel('Y') plt.title('Sparse Exponential Regression Example') plt.show()
Editor is loading...
Leave a Comment