Python中的多项式回归曲线

问题描述

我正在尝试为数据创建2度的回归曲线。创建图形时,我得到了一个有趣的zigzag东西,但是我想将数据建模为实际曲线,看起来像scatter图的连接版本。有什么建议/更好的方法吗?

degree = 2
p = np.poly1d(np.polyfit(data['input'],y,degree))
plt.plot(data['input'],p(data['input']),c='r',linestyle='-')
plt.scatter(data['input'],c='b')

在这里,data ['input']是具有与y相同尺寸的列向量。

编辑:我也这样尝试过:

X,y = np.array(data['input']).reshape(-1,1),np.array(data['output'])
lin_reg=LinearRegression(fit_intercept=False)
lin_reg.fit(X,y)

poly_reg=PolynomialFeatures(degree=2)
X_poly=poly_reg.fit_transform(X)
poly_reg.fit(X_poly,y)
lin_reg2=LinearRegression(fit_intercept=False)
lin_reg2.fit(X_poly,y)

X_grid=np.arange(min(X),max(X),0.1)
X_grid=X_grid.reshape((len(X_grid),1))
plt.scatter(X,color='red')
plt.plot(X,lin_reg2.predict(poly_reg.fit_transform(X)),color='blue')
plt.show()

哪个给我这张图here。散点图是我的数据,蓝色之字形是建模数据的二次曲线。帮助吗?

解决方法

在绘图中,您只是用直线在点到点之间进行绘图(其中y值是从polyfit函数得到的近似y)。

我将跳过polyfit函数(因为您拥有所有感兴趣的y值),而仅使用data['input']中的BSplines函数y内插make_interp_splinescipy并用您感兴趣的x范围绘制新的y值。

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as interp

仅点对点地弯曲(曲折)

x = np.array([1,2,3,4])
y = np.array([75,25,100])
plt.plot(x,y)

内插点

x_new = np.linspace(1,4,300)
a_BSpline = interp.make_interp_spline(x,y)
y_new = a_BSpline(x_new)
plt.plot(x_new,y_new)

尝试一下,然后根据您的数据进行调整! :)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...