R到Python / Numpy线性回归曲线

时间:2018-11-10 06:49:46

标签: python numpy linear-regression

学习python / numpy并想知道是否有人可以帮助将线性回归曲线方程从R转换为python / numpy?

library(zoo)
inertiaTS <- function(y, n) {
  x <- 1:n;
  c.ab=rollapply(y,n,function(yt){
    coef(lm(yt~x))
  },align = "right")                                                                                                                    
  plot(y,col=2)
  lines(c.ab[ ,2]*x[n]+c.ab[ ,1],col=4,lwd=2)
  list(axpb=c.ab[ ,2]*x[n]+c.ab[ ,1],rolcoef=c.ab)
}

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解您的要求,但是如果您想在python中拟合(线性回归)某些数据并将其绘制,则可以使用以下代码:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit


#just some data. Make sure that they are stored in an array, not in a list!!!:
y = np.array([1, 3.8, 7.1, 10.6, 12.6])
x = np.array([0, 1, 2, 3, 4])


#make sure that x is the first argument of linFunc!!
def linFunc(x, k, d):
    return k*x+d

#fitting Algorythm. cop gives you the 'best' values of k and d, cov is the covariance Matrix.
cop, cov = curve_fit(linFunc, x, y)

xplot = np.linspace(0, 4, 10**4)
plt.figure("data and fitted line")
plt.plot(x, y, 'ro', label = "datapoints")
plt.plot(xplot, linFunc(xplot, *cop), 'b--', label = "fittet function")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.legend()
plt.show()