Polynomial Fittings¶
In [1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# -----------------------------
# 1. Create Sample Data (Replace this with your file loading)
# -----------------------------
# Generate synthetic data with some noise (e.g., a cubic relationship)
np.random.seed(42)
X = np.linspace(-3, 3, 50)
true_Y = 0.5 * X**3 - 2 * X**2 + 5 * X + 10
Y = true_Y + np.random.normal(0, 5, 50)
# Create a DataFrame (mimics loading from a CSV)
df = pd.DataFrame({'Input_X': X, 'Output_Y': Y})
# -----------------------------
# 2. Define Parameters
# -----------------------------
# *** IMPORTANT: Change these to match your DataFrame columns ***
X_COLUMN = 'Input_X'
Y_COLUMN = 'Output_Y'
POLYNOMIAL_DEGREE = 3
# -----------------------------
# 3. Perform Polynomial Fitting
# -----------------------------
# Extract X and Y data
x_data = df[X_COLUMN]
y_data = df[Y_COLUMN]
# Use np.polyfit to calculate the coefficients (e.g., for a 3rd degree polynomial)
coefficients = np.polyfit(x_data, y_data, POLYNOMIAL_DEGREE)
# Use np.poly1d to create a callable polynomial function from the coefficients
polynomial_function = np.poly1d(coefficients)
# Generate Y values for the fitted line
x_fit = np.linspace(x_data.min(), x_data.max(), 100)
y_fit = polynomial_function(x_fit)
# -----------------------------
# 4. Visualization (Plotting)
# -----------------------------
plt.figure(figsize=(10, 6))
# Plot the original data points
plt.scatter(x_data, y_data, label='Original Data', color='darkblue', alpha=0.6)
# Plot the fitted polynomial curve
plt.plot(x_fit, y_fit, label=f'Polynomial Fit (Degree {POLYNOMIAL_DEGREE})', color='red', linewidth=2)
plt.title(f'Polynomial Regression (Degree {POLYNOMIAL_DEGREE})')
plt.xlabel(X_COLUMN)
plt.ylabel(Y_COLUMN)
plt.legend()
plt.grid(True, linestyle='--', alpha=0.6)
plt.tight_layout()
plt.savefig('polynomial_fit_example.png')
print(f"Polynomial Coefficients (from highest degree to constant term): {coefficients}")
print(f"Fitted Polynomial Equation: \n{polynomial_function}")
Polynomial Coefficients (from highest degree to constant term): [ 0.29228664 -1.70256003 5.68361597 7.94388934]
Fitted Polynomial Equation:
3 2
0.2923 x - 1.703 x + 5.684 x + 7.944
In [ ]: