如何绘制多项式回归的递增学习曲线

问题描述 投票:0回答:1

我正在尝试通过以下代码使用多项式特征来绘制拟合曲线,但是它并不正确。如何只绘制一条拟合曲线?

import matplotlib.pyplot as plt
import numpy as np

m = 100
X = 6 * np.random.rand(m,1) - 3
Y = 0.5 * X**2 + X + 2 + np.random.randn(m,1)

from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

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

lin = LinearRegression()

lin.fit(X_poly,Y)
Y_pred = lin.predict(X_poly)

plt.scatter(X, Y)
plt.plot(X_poly,Y_pred,color='red')
plt.show()

Click to see the matplotlib plot

python-3.x matplotlib scikit-learn linear-regression non-linear-regression
1个回答
0
投票

尝试:

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
m = 100
X = 6 * np.random.rand(m) - 3
Y = 0.5 * X**2 + X + 2 + np.random.randn(m)

from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

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

lin = LinearRegression()

lin.fit(X_poly,Y)
Y_pred = lin.predict(X_poly)

idx = X.argsort()

plt.scatter(X, Y)
plt.plot(X[idx],Y_pred[idx],color='red')
plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.