Python 无法正确拟合多项式回归线

Python 无法正确拟合多项式回归线,python,scikit-learn,regression,polynomials,Python,Scikit Learn,Regression,Polynomials,我有一个如下所示的数据帧: price | Sales 6.62 | 64.8 8.71 | 38 看起来像这样 我不太熟悉非线性回归,但在一些教程之后,我使用了以下代码来拟合多项式分布: X = df['price'].values y = df['sales'].values X = X.reshape(-1,1) from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model i

我有一个如下所示的数据帧:

price |  Sales
6.62  |  64.8
8.71  |  38
看起来像这样

我不太熟悉非线性回归,但在一些教程之后,我使用了以下代码来拟合多项式分布:

X = df['price'].values
y = df['sales'].values

X = X.reshape(-1,1)

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

pre_process = PolynomialFeatures(degree=2)
X_poly = pre_process.fit_transform(X)

pr_model = LinearRegression()
# Fit our preprocessed data to the polynomial regression model
pr_model.fit(X_poly, y)
# Store our predicted Humidity values in the variable y_new
y_pred = pr_model.predict(X_poly)
# Plot our model on our data
plt.scatter(X, y, c = "black")
plt.plot(X, y_pred)
我知道这是错误的:


是否知道我遗漏了什么,我无法获得合适的拟合线?

预测是正确的:

X = np.random.uniform(0,1,100)
y = 3*X**2 + 2*X - 8 + np.random.normal(0,1,100)

X = X.reshape(-1,1)

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

pre_process = PolynomialFeatures(degree=2)
X_poly = pre_process.fit_transform(X)

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

y_pred = pr_model.predict(X_poly)

plt.scatter(X, y, c = "black")
plt.scatter(X, y_pred, c="orange")

要绘制直线,需要对x值进行排序:

plt.scatter(X, y, c = "black")
x_sorted = np.sort(X,axis=0)
y_pred_sorted = pr_model.predict(pre_process.fit_transform(x_sorted))
plt.plot(x_sorted,y_pred_sorted,c="orange")