numpy - Python中的多元线性回归

我似乎无法找到任何进行多重回归的python库。 我发现的唯一的东西只做简单的回归。 我需要对几个自变量(x1,x2,x3等)回归我的因变量(y)。

例如,使用此数据:

print 'y x1 x2 x3 x4 x5 x6 x7'

for t in texts:

print "{:>7.1f}{:>10.2f}{:>9.2f}{:>9.2f}{:>10.2f}{:>7.2f}{:>7.2f}{:>9.2f}" /

.format(t.y,t.x1,t.x2,t.x3,t.x4,t.x5,t.x6,t.x7)

(以上输出:)

y x1 x2 x3 x4 x5 x6 x7

-6.0 -4.95 -5.87 -0.76 14.73 4.02 0.20 0.45

-5.0 -4.55 -4.52 -0.71 13.74 4.47 0.16 0.50

-10.0 -10.96 -11.64 -0.98 15.49 4.18 0.19 0.53

-5.0 -1.08 -3.36 0.75 24.72 4.96 0.16 0.60

-8.0 -6.52 -7.45 -0.86 16.59 4.29 0.10 0.48

-3.0 -0.81 -2.36 -0.50 22.44 4.81 0.15 0.53

-6.0 -7.01 -7.33 -0.33 13.93 4.32 0.21 0.50

-8.0 -4.46 -7.65 -0.94 11.40 4.43 0.16 0.49

-8.0 -11.54 -10.03 -1.03 18.18 4.28 0.21 0.55

我如何在python中回归这些,以获得线性回归公式:

Y = a1x1 + a2x2 + a3x3 + a4x4 + a5x5 + a6x6 + + a7x7 + c

11个解决方案

90 votes

sklearn.linear_model将做到这一点:

from sklearn import linear_model

clf = linear_model.LinearRegression()

clf.fit([[getattr(t, 'x%d' % i) for i in range(1, 8)] for t in texts],

[t.y for t in texts])

那么sklearn.linear_model将具有回归系数。

sklearn.linear_model也有类似的接口,可以对回归进行各种规范化。

Dougal answered 2019-07-04T01:27:06Z

57 votes

这是我创建的一个小工作。 我用R检查它,它的工作正常。

import numpy as np

import statsmodels.api as sm

y = [1,2,3,4,3,4,5,4,5,5,4,5,4,5,4,5,6,5,4,5,4,3,4]

x = [

[4,2,3,4,5,4,5,6,7,4,8,9,8,8,6,6,5,5,5,5,5,5,5],

[4,1,2,3,4,5,6,7,5,8,7,8,7,8,7,8,7,7,7,7,7,6,5],

[4,1,2,5,6,7,8,9,7,8,7,8,7,7,7,7,7,7,6,6,4,4,4]

]

def reg_m(y, x):

ones = np.ones(len(x[0]))

X = sm.add_constant(np.column_stack((x[0], ones)))

for ele in x[1:]:

X = sm.add_constant(np.column_stack((ele, X)))

results = sm.OLS(y, X).fit()

return results

结果:

print reg_m(y, x).summary()

输出:

OLS Regression Results

==============================================================================

Dep. Variable: y R-squared: 0.535

Model: OLS Adj. R-squared: 0.461

Method: Least Squares F-statistic: 7.281

Date: Tue, 19 Feb 2013 Prob (F-statistic): 0.00191

Time: 21:51:28 Log-Likelihood: -26.025

No. Observations: 23 AIC: 60.05

Df Residuals: 19 BIC: 64.59

Df Model: 3

==============================================================================

coef std err t P>|t| [95.0% Conf. Int.]

------------------------------------------------------------------------------

x1 0.2424 0.139 1.739 0.098 -0.049 0.534

x2 0.2360 0.149 1.587 0.129 -0.075 0.547

x3 -0.0618 0.145 -0.427 0.674 -0.365 0.241

const 1.5704 0.633 2.481 0.023 0.245 2.895

==============================================================================

Omnibus: 6.904 Durbin-Watson: 1.905

Prob(Omnibus): 0.032 Jarque-Bera (JB): 4.708

Skew: -0.849 Prob(JB): 0.0950

Kurtosis: 4.426 Cond. No. 38.6

pandas提供了一种运行OLS的便捷方式,如下面的答案所示:

使用Pandas Dataframe运行OLS回归

Akavall answered 2019-07-04T01:27:49Z

44 votes

只是为了澄清,你给出的例子是多元线性回归,而不是多元线性回归参考。 区别:

单个标量预测变量x和单个标量响应变量y的最简单情况称为简单线性回归。 多个和/或向量值预测变量的扩展(用大写X表示)称为多元线性回归,也称为多变量线性回归。 几乎所有现实世界的回归模型都涉及多个预测因子,线性回归的基本描述通常用多元回归模型来表达。 但请注意,在这些情况下,响应变量y仍然是标量。 另一个术语多元线性回归指的是y是矢量的情况,即与一般线性回归相同的情况。 应强调多元线性回归与多变量线性回归之间的差异,因为它会在文献中引起很多混淆和误解。

简而言之:

多元线性回归:响应y是标量。

多元线性回归:响应y是向量。

(另一个来源。)

Franck Dernoncourt answered 2019-07-04T01:28:46Z

26 votes

你可以使用numpy.linalg.lstsq:

import numpy as np

y = np.array([-6,-5,-10,-5,-8,-3,-6,-8,-8])

X = np.array([[-4.95,-4.55,-10.96,-1.08,-6.52,-0.81,-7.01,-4.46,-11.54],[-5.87,-4.52,-11.64,-3.36,-7.45,-2.36,-7.33,-7.65,-10.03],[-0.76,-0.71,-0.98,0.75,-0.86,-0.50,-0.33,-0.94,-1.03],[14.73,13.74,15.49,24.72,16.59,22.44,13.93,11.40,18.18],[4.02,4.47,4.18,4.96,4.29,4.81,4.32,4.43,4.28],[0.20,0.16,0.19,0.16,0.10,0.15,0.21,0.16,0.21],[0.45,0.50,0.53,0.60,0.48,0.53,0.50,0.49,0.55]])

X = X.T # transpose so input vectors are along the rows

X = np.c_[X, np.ones(X.shape[0])] # add bias term

beta_hat = np.linalg.lstsq(X,y)[0]

print beta_hat

结果:

[ -0.49104607 0.83271938 0.0860167 0.1326091 6.85681762 22.98163883 -41.08437805 -19.08085066]

您可以通过以下方式查看估算输出:

print np.dot(X,beta_hat)

结果:

[ -5.97751163, -5.06465759, -10.16873217, -4.96959788, -7.96356915, -3.06176313, -6.01818435, -7.90878145, -7.86720264]

Imran answered 2019-07-04T01:29:21Z

11 votes

使用scipy.optimize.curve_fit.而不仅仅是线性拟合。

from scipy.optimize import curve_fit

import scipy

def fn(x, a, b, c):

return a + b*x[0] + c*x[1]

# y(x0,x1) data:

# x0=0 1 2

# ___________

# x1=0 |0 1 2

# x1=1 |1 2 3

# x1=2 |2 3 4

x = scipy.array([[0,1,2,0,1,2,0,1,2,],[0,0,0,1,1,1,2,2,2]])

y = scipy.array([0,1,2,1,2,3,2,3,4])

popt, pcov = curve_fit(fn, x, y)

print popt

Volodimir Kopey answered 2019-07-04T01:29:45Z

8 votes

将数据转换为pandas数据帧(df)后,

import statsmodels.formula.api as smf

lm = smf.ols(formula='y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7', data=df).fit()

print(lm.params)

截距项默认包含在内。

有关更多示例,请参阅此笔记本

canary_in_the_data_mine answered 2019-07-04T01:30:23Z

4 votes

我认为这可能是完成这项工作最简单的方法:

from random import random

from pandas import DataFrame

from statsmodels.api import OLS

lr = lambda : [random() for i in range(100)]

x = DataFrame({'x1': lr(), 'x2':lr(), 'x3':lr()})

x['b'] = 1

y = x.x1 + x.x2 * 2 + x.x3 * 3 + 4

print x.head()

x1 x2 x3 b

0 0.433681 0.946723 0.103422 1

1 0.400423 0.527179 0.131674 1

2 0.992441 0.900678 0.360140 1

3 0.413757 0.099319 0.825181 1

4 0.796491 0.862593 0.193554 1

print y.head()

0 6.637392

1 5.849802

2 7.874218

3 7.087938

4 7.102337

dtype: float64

model = OLS(y, x)

result = model.fit()

print result.summary()

OLS Regression Results

==============================================================================

Dep. Variable: y R-squared: 1.000

Model: OLS Adj. R-squared: 1.000

Method: Least Squares F-statistic: 5.859e+30

Date: Wed, 09 Dec 2015 Prob (F-statistic): 0.00

Time: 15:17:32 Log-Likelihood: 3224.9

No. Observations: 100 AIC: -6442.

Df Residuals: 96 BIC: -6431.

Df Model: 3

Covariance Type: nonrobust

==============================================================================

coef std err t P>|t| [95.0% Conf. Int.]

------------------------------------------------------------------------------

x1 1.0000 8.98e-16 1.11e+15 0.000 1.000 1.000

x2 2.0000 8.28e-16 2.41e+15 0.000 2.000 2.000

x3 3.0000 8.34e-16 3.6e+15 0.000 3.000 3.000

b 4.0000 8.51e-16 4.7e+15 0.000 4.000 4.000

==============================================================================

Omnibus: 7.675 Durbin-Watson: 1.614

Prob(Omnibus): 0.022 Jarque-Bera (JB): 3.118

Skew: 0.045 Prob(JB): 0.210

Kurtosis: 2.140 Cond. No. 6.89

==============================================================================

xmduhan answered 2019-07-04T01:30:49Z

4 votes

可以使用上面引用的sklearn库来处理多元线性回归。 我使用的是Anaconda安装的Python 3.6。

按如下方式创建模型:

from sklearn.linear_model import LinearRegression

regressor = LinearRegression()

regressor.fit(X, y)

# display coefficients

print(regressor.coef_)

Eric C. Bohn answered 2019-07-04T01:31:21Z

3 votes

您可以使用numpy.linalg.lstsq

Moukden answered 2019-07-04T01:31:46Z

1 votes

您可以使用下面的函数并将其传递给DataFrame:

def linear(x, y=None, show=True):

"""

@param x: pd.DataFrame

@param y: pd.DataFrame or pd.Series or None

if None, then use last column of x as y

@param show: if show regression summary

"""

import statsmodels.api as sm

xy = sm.add_constant(x if y is None else pd.concat([x, y], axis=1))

res = sm.OLS(xy.ix[:, -1], xy.ix[:, :-1], missing='drop').fit()

if show: print res.summary()

return res

Alpha answered 2019-07-04T01:32:12Z

0 votes

这是一种替代的基本方法:

from patsy import dmatrices

import statsmodels.api as sm

y,x = dmatrices("y_data ~ x_1 + x_2 ", data = my_data)

### y_data is the name of the dependent variable in your data ###

model_fit = sm.OLS(y,x)

results = model_fit.fit()

print(results.summary())

您也可以使用sm.Logit或sm.Probit等代替sm.OLS。

newbiee answered 2019-07-04T01:32:45Z

python 多元线性回归_numpy - Python中的多元线性回归相关推荐

  1. sql 线性回归_SQL Server中的Microsoft线性回归

    sql 线性回归 In this article, we will be discussing Microsoft Linear Regression in SQL Server. This is t ...

  2. python多元线性回归模型案例_Python 实战多元线性回归模型,附带原理+代码

    原标题:Python 实战多元线性回归模型,附带原理+代码 作者 | 萝卜 来源 | 早起Python( ID:zaoqi-python ) 「多元线性回归模型」非常常见,是大多数人入门机器学习的第一 ...

  3. [转载] 多元线性回归 及其Python实现

    参考链接: 线性回归(Python实现) 多元线性回归 Python实现 多元线性回归求解过程 多元线性回归的形式:  目标函数:  将一个样本的向量化: 将所有样本的向量化:  向量化后的目标函数及 ...

  4. python多元回归预测例子_Python机器学习,多元线性回归分析问题

    @Author:润森,Runsen,公众号:润森笔记 什么是多元线性回归 在回归分析中,如果有两个或两个以上的自变量,就称为多元回归.**事实上,一种现象常常是与多个因素相联系的,由多个自变量的最优组 ...

  5. 数据分析记录(六)--多元线性回归在SPSS中的实现(步骤及指标含义)

    数据分析记录(六)–多元线性回归在SPSS中的实现(步骤及指标含义) 本文仅作为自己的学习记录以备以后复习查阅 在回归分析中,如果有两个或两个以上的自变量,就称为多元回归.事实上,一种现象常常是与多个 ...

  6. Python数模笔记-Sklearn(4)线性回归

    1.什么是线性回归? 回归分析(Regression analysis)是一种统计分析方法,研究自变量和因变量之间的定量关系.回归分析不仅包括建立数学模型并估计模型参数,检验数学模型的可信度,也包括利 ...

  7. python f检验 模型拟合度_python数据分析之线性回归,各种检验和解决方法!

    线性回归 (1)线性回归的主要内容: 有兴趣可以玩一下这个游戏:是猜相关系数的,给你一些散点图,猜相关系数,很难猜对,说明看图说明相关性不靠谱! (2)线性回归怎么做?数学公式 一个简单线性回归的例子 ...

  8. python计算平方面积_python中求平方

    python学习(2)--变量与表达式 python学习(2)--变量与表达式 1.与java和c语言相通,python中也分为四种运算符: (1)算数运算符(如:+.-.*./); 学过java或者 ...

  9. Python Train_机器学习--基于Python的简单线性回归

    一.概念 线性回归(Linear regression)是利用称为线性回归方程的最小二乘函数对一个或多个自变量和因变量之间关系进行建模的一种回归分析. 这种函数是一个或多个称为回归系数的模型参数的线性 ...

最新文章

  1. 第一次体验python有感
  2. mybatis可以生成不重复的id吗_Mybatis面试题吐血总结
  3. php mongo 范围查询语句,【MongoDB】数组和范围查询的相互作用
  4. mac bash file密码_MAC 常用命令汇总
  5. jaegeropentracing的Java-client
  6. Prometheus Operator 架构 - 每天5分钟玩转 Docker 容器技术(178)
  7. 并发编程学习之JDK1.8的ConcurrentHashMap
  8. 参考文献格式字号字体_论文格式字体字号要求
  9. 江苏计算机二级msoffice高级应用,计算机二级考试MSOffice高级应用
  10. 【Keil变量定义】定义extern类型变量
  11. Recipe 1.5. Trimming Space from the Ends of a String(Python Cookbook)
  12. ja_charity模板研究_contin_1
  13. 病人信息管理html,基于JSP住院病人信息管理系统本科.doc
  14. 追风筝的人 第一章
  15. WIFI-TTL透传模块
  16. 均值不等式的来龙去脉
  17. Mysql之一台服务器上装多个mysql-yellowcong
  18. eclipse 自动提示报错解决方案
  19. 【快速文档】ad标签,我想通过小程序流量主赚钱,应该怎样做
  20. 给你的iPhone桌面加个分层特效,有趣!

热门文章

  1. 實用英語吵架一百句....
  2. 行云管家堡垒机和传统堡垒机的区别简单讲解
  3. 泛微ecology 选择框的查询
  4. AE/PR/OFX插件-Mocha Pro 2023 v10.0.2 Win 专业平面/三维跟踪摄像机反求插件
  5. win7开启iis服务
  6. 在启动 sql2000 服务时提示: 错误 1609 由于登录失败无法启动服务
  7. go每日新闻--2020-05-20
  8. 开关4元、瓷砖7.8元、地板79.... 3.30日广州惊现2014最低价!
  9. OSPF知识汇总及配置——超详细!!
  10. FPGA设计交通信号灯(verilog)