2도 선형 회귀 플로팅의 어려움

Aug 25 2020

기계 학습 모델에서 2도 곡선으로 2D 선형 회귀를 그리는 동안 문제가 있습니다.

내 코드는 다음과 같습니다.

m = 100
X = 6 * np.random.rand(m, 1) - 3

y = 0.5 * X**2 + X + 2 + np.random.randn(m, 1)
plt.plot(X, y, "b.")
plt.show() 

여기까지 괜찮습니다. 이것은 내 산점도입니다.

이제 2도 선형 모델을 훈련하고 있습니다.

from sklearn.preprocessing import PolynomialFeatures

poly_features = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly_features.fit_transform(X)

lin_reg = LinearRegression()
lin_reg.fit(X_poly, y)

훈련 된 모델.

그리고 이것은 곡선을 그릴 때의 결과입니다.

plt.plot(X, lin_reg.predict(X_poly), "r-")
plt.show()

선으로 연결된 점이 아니라 연속 곡선을 인쇄하는 방법을 알아 내고 있습니다.

아래는 내가 원하는 출력이며 수동으로 그립니다.

답변

2 TrentonMcKinney Aug 25 2020 at 12:17
  • 너 자신을 차게 될거야 아마
  • X로 정렬해야하는 것을 제외하고는 모든 것이 numpy.sort()좋습니다.
    • 선은 점에서 점으로 순서대로 그려집니다. 포인트는에 의해 정렬되지 않았기 때문에 X전체에 그려집니다.
  • np.random.seed(365) 매번 동일한 값을 생성하도록 지정되었습니다.
import numpy
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

m = 100
np.random.seed(365)
X = 6 * np.random.rand(m, 1) - 3
X = np.sort(X, axis=0)  # sort the values

y = 0.5 * X**2 + X + 2 + np.random.randn(m, 1)

# regression code
poly_features = PolynomialFeatures(degree=2, include_bias=False)
X_poly = poly_features.fit_transform(X)

lin_reg = LinearRegression()
lin_reg.fit(X_poly, y)

# plot
plt.plot(X, y, "b.")
plt.plot(X, lin_reg.predict(X_poly), "r-")
plt.show()