【问题标题】:How to know the equation of the fitting curve如何知道拟合曲线的方程
【发布时间】:2022-01-01 07:23:11
【问题描述】:

我想问一下, 如何知道拟合曲线的方程?尤其是3级。 因此,我使用 3 度线性回归拟合我的数据。 我想将拟合曲线拆分成单独的图形。

    # Fitting Polynomial Regression to the dataset
# we use orde 2 for our Polynomial
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import r2_score

poly_reg1 = PolynomialFeatures(degree= 1)
x_poly1 = poly_reg1.fit_transform(x1)
pol_reg1 = LinearRegression()
pol_reg1.fit(x_poly1, y1)

poly_reg2 = PolynomialFeatures(degree= 3)
x_poly2 = poly_reg2.fit_transform(x2)
pol_reg2 = LinearRegression()
pol_reg2.fit(x_poly2, y2)
    
# find R2 value 
y_poly_pred1=pol_reg1.predict(x_poly1)
r2_1 = r2_score(x1,y_poly_pred1)

y_poly_pred2=pol_reg2.predict(x_poly2)
r2_2 = r2_score(x2,y_poly_pred2)

# Visualizing the Polymonial Regression results
plt.scatter(x1, y1, color='blue')
plt.plot(x1, pol_reg1.predict(poly_reg1.fit_transform(x1)), color='magenta')
plt.scatter(x2, y2, color='black')
plt.plot(x2, pol_reg2.predict(poly_reg2.fit_transform(x2)), color='red')

plt.title('EAN vs ln I_m')
plt.xlabel('EAN')
plt.ylabel('ln I_m')
plt.show()

print('r2_1 is '+ str(r2_1))
print('r2_2 is '+ str(r2_2))

【问题讨论】:

  • 澄清问题:您需要方程本身还是仅仅为了能够绘制模型?

标签: python regression curve-fitting


【解决方案1】:

如果您只需要绘制模型(假设 x1x2 是一维的),您可以使用

xg = np.linspace(xmin, xmax, 300)
plt.plot(xg, pol_reg1.predict(poly_reg1.transform(xg)), color='magenta')
plt.plot(xg, pol_reg2.predict(poly_reg2.transform(xg)), color='red')

其中xminxmax 表示您希望在其之间绘制模型的最小值和最大值。

【讨论】:

    猜你喜欢
    • 2015-03-02
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 2017-08-04
    • 2019-11-14
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多