线性回归-python实现的5种方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | import numpy as np from scipy.stats import linregress import statsmodels.api as sm import matplotlib.pyplot as plt from gekko import GEKKO # Data x = np.array([ 4 , 5 , 2 , 3 , - 1 , 1 , 6 , 7 ]) y = np.array([ 0.3 , 0.8 , - 0.05 , 0.1 , - 0.8 , - 0.5 , 0.5 , 0.65 ]) # calculate R^2 def rsq(y1,y2): yresid = y1 - y2 SSresid = np. sum (yresid * * 2 ) SStotal = len (y1) * np.var(y1) r2 = 1 - SSresid / SStotal return r2 # Method 1: scipy linregress slope,intercept,r,p_value,std_err = linregress(x,y) a = [slope,intercept] print ( 'R^2 linregress = ' + str (r * * 2 )) # Method 2: numpy polyfit (1=linear) a = np.polyfit(x,y, 1 ); print (a) yfit = np.polyval(a,x) print ( 'R^2 polyfit = ' + str (rsq(y,yfit))) # Method 3: numpy linalg solution # y = X a # X^T y = X^T X a X = np.vstack((x,np.ones( len (x)))).T # matrix operations XX = np.dot(X.T,X) XTy = np.dot(X.T,y) a = np.linalg.solve(XX,XTy) # same solution with lstsq a = np.linalg.lstsq(X,y,rcond = None )[ 0 ] yfit = a[ 0 ] * x + a[ 1 ]; print (a) print ( 'R^2 matrix = ' + str (rsq(y,yfit))) # Method 4: statsmodels ordinary least squares X = sm.add_constant(x,prepend = False ) model = sm.OLS(y,X).fit() yfit = model.predict(X) a = model.params print (model.summary()) # Method 5: Gekko for constrained regression m = GEKKO(remote = False ); m.options.IMODE = 2 c = m.Array(m.FV, 2 ); c[ 0 ].STATUS = 1 ; c[ 1 ].STATUS = 1 c[ 1 ].lower = - 0.5 xd = m.Param(x); yd = m.Param(y); yp = m.Var() m.Equation(yp = = c[ 0 ] * xd + c[ 1 ]) m.Minimize((yd - yp) * * 2 ) m.solve(disp = False ) c = [c[ 0 ].value[ 0 ],c[ 1 ].value[ 1 ]] print (c) # plot data and regressed line plt.plot(x,y, 'ko' ,label = 'data' ) xp = np.linspace( - 2 , 8 , 100 ) slope = str (np. round (a[ 0 ], 2 )) intercept = str (np. round (a[ 1 ], 2 )) eqn = 'LstSQ: y=' + slope + 'x' + intercept plt.plot(xp,a[ 0 ] * xp + a[ 1 ], 'r-' ,label = eqn) slope = str (np. round (c[ 0 ], 2 )) intercept = str (np. round (c[ 1 ], 2 )) eqn = 'Constraint: y=' + slope + 'x' + intercept plt.plot(xp,c[ 0 ] * xp + c[ 1 ], 'b--' ,label = eqn) plt.grid() plt.legend() plt.show() |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人