R语言三次正交多项式拟合绘图异常问题求助
Hey there! Let's break down why you're seeing those messy multiple regression lines when fitting cubic orthogonal polynomials and comparing them to 7th-degree fits. Here are the most common culprits and how to fix them:
1. Accumulated Plots from Uncontrolled Loops
If you're using a loop to fit polynomials or iterate over data, forgetting to reset your plot canvas will stack every line onto the same figure. This makes it look like a jumble of random lines instead of clean comparisons.
How to Check & Fix:
Look for code where you call plt.plot() inside a loop without initializing a new figure first. Add plt.figure() at the start of your plotting code, or use plt.clf() to clear the current figure before drawing new lines.
Example of clean plotting:
import matplotlib.pyplot as plt import numpy as np from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression # Your sample data (replace with your actual data) x = np.linspace(0, 10, 100).reshape(-1, 1) y = np.sin(x) + np.random.normal(0, 0.1, x.shape) # Start with a fresh canvas plt.figure(figsize=(10, 6)) # Fit & plot cubic polynomial poly_cubic = PolynomialFeatures(degree=3, include_bias=False) x_cubic = poly_cubic.fit_transform(x) model_cubic = LinearRegression() model_cubic.fit(x_cubic, y) y_pred_cubic = model_cubic.predict(x_cubic) plt.plot(x, y_pred_cubic, label='Cubic (3rd Degree)', color='navy') # Fit & plot 7th-degree polynomial poly_7th = PolynomialFeatures(degree=7, include_bias=False) x_7th = poly_7th.fit_transform(x) model_7th = LinearRegression() model_7th.fit(x_7th, y) y_pred_7th = model_7th.predict(x_7th) plt.plot(x, y_pred_7th, label='7th Degree', color='crimson') # Add raw data for context plt.scatter(x, y, alpha=0.3, label='Raw Data') plt.legend() plt.show()
2. Buggy Orthogonal Polynomial Implementation
If you're manually coding orthogonal polynomials (instead of using library functions), it's easy to mess up the basis function calculations. This can lead to incorrect feature matrices, which make the model fit garbage lines.
How to Check & Fix:
- If you're rolling your own orthogonal polynomials (like Legendre or Chebyshev), double-check your recurrence relations and feature scaling.
- For a safer approach, use
numpy's built-in orthogonal polynomial classes:
from numpy.polynomial.legendre import Legendre # Fit cubic orthogonal Legendre polynomial legendre_cubic = Legendre.fit(x.flatten(), y.flatten(), 3) y_pred_legendre = legendre_cubic(x.flatten()) plt.plot(x, y_pred_legendre, label='Cubic Orthogonal (Legendre)', color='forestgreen')
3. Unintended Data Grouping or Duplicate Values
If your dataset has duplicate x-values, or you're accidentally iterating over groups in your data without separating plots, each group's fit line will get drawn on the same figure.
How to Check & Fix:
- Print the shape of your
xandyarrays to confirm they're 1D (or 2D with one feature) for a single fit. - If you have grouped data, use subplots (
plt.subplots()) to plot each group separately instead of stacking them.
4. Plotting Raw Y-Values Instead of Predictions
It's easy to mix up variables and pass your raw y data to plt.plot() instead of the model's predicted y_pred values. This will draw a messy line connecting all your data points, which looks like multiple regression lines.
How to Check & Fix:
Double-check the second argument in your plt.plot() calls—make sure it's the output of your model's .predict() method, not your original target variable.
If none of these fix your issue, share a snippet of your code and a small sample of your data, and I can help dig deeper!
内容的提问来源于stack exchange,提问作者user1607

