Untitled

 avatar
unknown
plain_text
10 months ago
1.4 kB
11
Indexable
import numpy as np
import matplotlib.pyplot as plt

# Assume data arrays x1, x2 exist (same length). x1 is independent, x2 is dependent.
# Example: x1 = df['x1'].to_numpy(); x2 = df['x2'].to_numpy()

# 1) Randomly sample 10 points reproducibly
np.random.seed(100)

rng = np.random.default_rng(0); 
x1 = np.linspace(-3, 3, 60); 
x2 = 0.5*x1**2 - x1 + 2 + rng.normal(0, 0.5, size=x1.size)

n = len(x1)
idx = np.random.choice(n, size=10, replace=False)
x = x1[idx]
y = x2[idx]

# 2) Fit polynomial models of specified degrees
degrees = [0, 1, 2, 3, 4, 9]
models = {}
for d in degrees:
    coefs = np.polyfit(x, y, deg=d)
    models[d] = np.poly1d(coefs)

# 3) Compute errors (MSE) on the 10 training points
def mse(y_true, y_pred):
    return np.mean((y_true - y_pred) ** 2)

errors = {d: mse(y, models[d](x)) for d in degrees}

# 4) Plot data and fitted curves
x_plot = np.linspace(x.min(), x.max(), 400)
plt.figure(figsize=(8, 6))
plt.scatter(x, y, color='k', label='Sampled data (n=10)')

colors = ['tab:blue','tab:orange','tab:green','tab:red','tab:purple','tab:brown']
for color, d in zip(colors, degrees):
    y_plot = models[d](x_plot)
    plt.plot(x_plot, y_plot, color=color, label=f'deg {d}, MSE={errors[d]:.3g}')

plt.xlabel('x1')
plt.ylabel('x2')
plt.title('Polynomial fits on 10-point subsample')
plt.legend()
plt.grid(True)
plt.show()

# 5) Report errors programmatically
for d in degrees:
    print(f"Degree {d}: MSE = {errors[d]:.6f}")
Editor is loading...
Leave a Comment