【问题标题】:Linear regression with defined intercept具有定义截距的线性回归
【发布时间】:2019-05-27 17:28:51
【问题描述】:

我有一个两列三行的 DataFrame (df)。

X 列 = [137,270,344] Y 列 = [51, 121, 136]

考虑到截距 = 0,我想得到线性回归的斜率。

我尝试添加一个点 (0,0),但它不起作用。

前。 X 列 = [0, 137,270,344] Y 列 = [0, 51, 121, 136]

我正在使用的代码。

代码:

X= df [“Column X”].astype(float)  
Y = df [“Column Y”].astype(float)  

slope, intercept, r_value, p_value, std_err = stats.linregress(X, Y)
intercept_desv = slope 
coef_desv = intercept  

我预计截距 = 0 但小于 0。

【问题讨论】:

  • 您希望它们在 0 处拦截还是希望它们在 0 处拦截?

标签: python pandas dataframe linear-regression


【解决方案1】:

在标准线性回归中,所有数据点的权重都隐含为 1.0。在任何允许使用权重进行线性回归的软件中,通过为该数据点分配一个非常大的权重,可以有效地使回归通过任何单个点(例如原点)。 Numpy 的 polyfit() 允许权重。这是一个使用此技术使拟合线通过 0,0 点的数据的图形示例。

import numpy, matplotlib
import matplotlib.pyplot as plt

xData = numpy.array( [0.0, 137.0, 270.0, 344.0])
yData = numpy.array([0.0, 51.0, 121.0, 136.0])

weights = numpy.array([1.0E10, 1.0, 1.0, 1.0]) # heavily weight the 0,0 point
#weights = None # use this for "no weights"

polynomialOrder = 1 # example straight line

# curve fit the test data
fittedParameters = numpy.polyfit(xData, yData, polynomialOrder, w=weights)
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()
print('Predicted value at x=0:', modelPredictions[0])
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)

【讨论】:

  • 谢谢!我将 np.polyfit 与权重配置一起使用,它起作用了!
  • 请记住,这与任何允许权重的软件的工作方式相同 - 很高兴知道。
猜你喜欢
  • 2018-06-11
  • 2011-11-12
  • 1970-01-01
  • 2022-01-09
  • 2020-12-03
  • 2015-10-28
  • 2016-08-31
  • 2021-10-25
  • 2020-10-28
相关资源
最近更新 更多