【问题标题】:Linear Regression with 3 input vectors and 4 output vectors?具有 3 个输入向量和 4 个输出向量的线性回归?
【发布时间】:2016-08-28 03:47:24
【问题描述】:

任务:

例如,我们有 3 个输入向量:

foo = [1, 2, 3, 4, 5, 6]
bar = [50, 60, 70, 80, 90, 100]
spam = [-10, -20, -30, -40, -50, -60]

此外,我们有 4 个输出向量与输入向量具有线性相关性:

foofoo = [1, 1, 2, 2, 3, 3]
barbar = [4, 4, 5, 5, 6, 6]
spamspam = [7, 7, 8, 8, 9, 9]
hamham = [10, 10, 11, 11, 12, 12]

如何在 Python 中对这些数据使用线性回归?

【问题讨论】:

标签: python numpy math scikit-learn linear-regression


【解决方案1】:

你可以像here一样使用OLS (Ordinary Least Squares model)

#imports
import numpy as np
import statsmodels.api as sm

#generate the input matrix
X=[foo,bar,spam]
#turn it into a numpy array
X = np.array(X).T
#add a constant column
X=sm.add_constant(X)

这给出了输入矩阵X

array([[   1.,    1.,   50.,  -10.],
       [   1.,    2.,   60.,  -20.],
       [   1.,    3.,   70.,  -30.],
       [   1.,    4.,   80.,  -40.],
       [   1.,    5.,   90.,  -50.],
       [   1.,    6.,  100.,  -60.]])

现在您可以拟合每个所需的输出向量:

resFoo = sm.OLS(endog=foofoo, exog=X).fit()
resBar = sm.OLS(endog=barbar, exog=X).fit()
resSpam = sm.OLS(endog=spamspam, exog=X).fit()
resham = sm.OLS(endog=hamham, exog=X).fit()

result 为您提供系数(对于常数,以及 foo、bar 和 spam 三列):

>>> resFoo.params
array([-0.00063323,  0.0035345 ,  0.01001583, -0.035345  ])

您现在可以通过输入检查它:

>>> np.matrix(X)*np.matrix(resFoo.params).T
matrix([[ 0.85714286],
        [ 1.31428571],
        [ 1.77142857],
        [ 2.22857143],
        [ 2.68571429],
        [ 3.14285714]])

这接近于foofoo 的期望输出。


有关进行回归的不同方法,请参阅此问题:Multiple linear regression in Python

【讨论】:

    猜你喜欢
    • 2020-10-13
    • 2021-05-07
    • 1970-01-01
    • 2019-05-11
    • 2018-10-13
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 2013-03-09
    相关资源
    最近更新 更多