简体   繁体   English

Python OLS计算

[英]Python OLS calculation

Is there any good library to calculate linear least squares OLS (Ordinary Least Squares) in python? 有没有好的库来计算python中的线性最小二乘OLS(普通最小二乘法)?

Thanks. 谢谢。

Edit: 编辑:

Thanks for the SciKits and Scipy. 感谢SciKits和Scipy。 @ars: Can X be a matrix? @ars:X可以是矩阵吗? An example: 一个例子:

y(1) = a(1)*x(11) + a(2)*x(12) + a(3)*x(13)
y(2) = a(1)*x(21) + a(2)*x(22) + a(3)*x(23)
...........................................
y(n) = a(1)*x(n1) = a(2)*x(n2) + a(3)*x(n3)

Then how do I pass the parameters for Y and X matrices in your example? 那么如何在示例中传递Y和X矩阵的参数?

Also, I don't have much background in algebra, I would appreciate if you guys can let me know a good tutorial for that kind of problems. 另外,我没有太多的代数背景,如果你们能让我知道这个问题的好教程,我将不胜感激。

Thanks much. 非常感谢。

Try the statsmodels package. 试试statsmodels包。 Here's a quick example: 这是一个简单的例子:

import pylab
import numpy as np
import statsmodels.api as sm

x = np.arange(-10, 10)
y = 2*x + np.random.normal(size=len(x))

# model matrix with intercept
X = sm.add_constant(x)

# least squares fit
model = sm.OLS(y, X)
fit = model.fit()

print fit.summary()

pylab.scatter(x, y)
pylab.plot(x, fit.fittedvalues)

Update In response to the updated question, yes it works with matrices. 更新响应更新的问题,是的,它适用于矩阵。 Note that the code above has the x data in array form, but we build a matrix X (capital X) to pass to OLS . 请注意,上面的代码具有数组形式的x数据,但我们构建了一个矩阵X (大写X)以传递给OLS The add_constant function simply builds the matrix with a first column initialized to ones for the intercept. add_constant函数只是构建矩阵,第一列初始化为拦截的列。 In your case, you would simply pass your X matrix without needing that intermediate step and it would work. 在您的情况下,您只需传递X矩阵而无需中间步骤,它就可以工作。

Have you looked at SciPy? 你看过SciPy吗? I don't know if it does that, but I would imagine it will. 我不知道是不是这样,但我想它会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM