【问题标题】:Linear Regression to fit 2D data in python在python中拟合二维数据的线性回归
【发布时间】: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)而不是手动计算XtXXtY、反相等。
  • Em,你的第二个情节是预测的错误?与真实数据相比,它平均减少了大约 31 个单位,我认为这不是一个好的结果。除此之外,你想拟合一条线还是一个多项式?
  • 感谢您的精彩回答。为了回答你的问题,我想拟合一个多项式。

标签: python machine-learning linear-regression


【解决方案1】:

这是一个图形示例多项式拟合器,使用 numpy 的 polyfit() 进行拟合,使用 numpy 的 polyval() 计算模型预测,以及 RMSE 和 R 平方值。

import numpy, scipy, matplotlib
import matplotlib.pyplot as plt

xData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.0, 6.6, 7.7, 0.0])
yData = numpy.array([1.1, 20.2, 30.3, 40.4, 50.0, 60.6, 70.7, 0.1])

polynomialOrder = 2 # example quadratic

# curve fit the test data
fittedParameters = numpy.polyfit(xData, yData, polynomialOrder)
print('Fitted Parameters:', fittedParameters)

modelPredictions = numpy.polyval(fittedParameters, xData)
absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()


##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = numpy.polyval(fittedParameters, xModel)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)

【讨论】:

  • 谢谢。该代码很有用,但我想自己编写这些预定义的 numpy 函数来真正理解整个过程。再次感谢。
猜你喜欢
  • 2017-02-24
  • 2020-04-20
  • 2020-10-22
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 2017-08-20
  • 2018-05-08
相关资源
最近更新 更多