【发布时间】:2018-10-25 18:57:46
【问题描述】:
我有一个函数 Polyfit 我希望它在这里获取数据 x 和 y 并使用线性回归返回适合该数据的 2D 线。我得到了一个很好的结果,但它太好了,我不知道我是否一直正确地做到最后。
#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--')
数据图:
拟合线的结果:
【问题讨论】:
-
为什么
np.vstack([np.ones(x.shape), x, y]).T中有一个Y? -
另外,您可以使用
np.stack((np.ones_like(x), x), axis=-1)。 -
更好的是,使用
np.linalg.lstsq(x, y)而不是手动计算XtX、XtY、反相等。 -
Em,你的第二个情节是预测的错误?与真实数据相比,它平均减少了大约 31 个单位,我认为这不是一个好的结果。除此之外,你想拟合一条线还是一个多项式?
-
感谢您的精彩回答。为了回答你的问题,我想拟合一个多项式。
标签: python machine-learning linear-regression