我有一个函数Polyfit,我希望它能得到x和y的数据,并用线性回归法返回一条二维线。我得到了一个很好的结果,但这太好了,我不知道我是否正确地做到了最后。在
#creating the data and plotting them
np.random.seed(0)
N = 10 # number of data points
x = np.linspace(0,2*np.pi,N)
y = np.sin(x) + np.random.normal(0,.3,x.shape)
plt.figure()
plt.plot(x,y,'o')
plt.xlabel('x')
plt.ylabel('y')
plt.title('2D data (#data = %d)' % N)
plt.show()
def polyfit(x,y,degree,delta):
#x,y
X = np.vstack([np.ones(x.shape), x, y]).T
Y = np.vstack([y]).T
XtX = np.dot(X.T, X)
XtY = np.dot(X.T, Y)
theta = np.dot(np.linalg.inv(XtX), XtY)
degree = theta.shape[0]
delta = theta.T * theta
x_theta = X.T * theta
pred = np.sum([theta* x])
loss = np.dot((Y.T - x_theta).T, (Y.T - x_theta))
c = theta[0] + theta[1] * x[1] + theta[2] * math.pow(x[2],2)
return pred
result = polyfit(x,y,2,2)
fin = y - result
plt.plot(x, fin, 'go--')
数据图片:
拟合结果:
下面是一个绘图示例多项式拟合器,使用numpy的polyfit()进行拟合,numpy的polyval()计算模型预测,以及RMSE和R平方值。在
相关问题 更多 >
编程相关推荐