如何使用scikit-learn对python中的数据集进行多元线性回归?

时间:2018-12-11 21:59:01

标签: python pandas scikit-learn linear-regression

我的python代码最初输出这些结果,一份人口普查区域(基本上是一块土地)人口的字典列表以及各种土地覆盖类型。这就是:

[{'Total Population:': 4585, 'Total Water Ice Cover': 2.848142234497044, 'Total Developed': 17.205368316575324, 'Total Barren Land': 0.22439908514219134, 'Total Forest': 34.40642126612868},

 {'Total Population:': 4751, 'Total Water Ice Cover': 1.047783534830167, 'Total Developed': 37.27115716753022, 'Total Barren Land': 0.11514104778353484, 'Total Forest': 19.11341393206678},

 {'Total Population:': 3214, 'Total Water Ice Cover': 0.09166603009701321, 'Total Developed': 23.50469788404247, 'Total Barren Land': 0.2597204186082041, 'Total Forest': 20.418608204109695},

 {'Total Population:': 5005, 'Total Water Ice Cover': 0.0, 'Total Developed': 66.37545713124746, 'Total Barren Land': 0.0, 'Total Forest': 10.68671271840715},

...
]

然后使用该代码将其放入pandas对象:

import pandas as pd
df = pd.DataFrame(output)
print(df)
#   Total Barren Land  Total Developed  Total Forest  Total Population:  Total Water Ice Cover
#0           0.224399        17.205368     34.406421               4585               2.848142 
#1           0.115141        37.271157     19.113414               4751               1.047784 
#2           0.259720        23.504698     20.418608               3214               0.091666   
#3           0.000000        66.375457     10.686713               5005               1.047784 

然后获得皮尔逊“ r”相关性:

pd.set_option("precision",4)  # only show 4 digits

# remove 'Total ' from column names to make printing smaller
df.rename(columns=lambda x: x.replace("Total ", ""), inplace=True)  

corr = df.corr(method="pearson")
print(corr)
#                 Barren Land  Developed  Forest  Population:  Water Ice Cover
#Barren Land           1.0000    -0.9579  0.7361      -0.7772           0.4001
#Developed            -0.9579     1.0000 -0.8693       0.5736          -0.6194
#Forest                0.7361    -0.8693  1.0000      -0.1575           0.9114
#Population:          -0.7772     0.5736 -0.1575       1.0000           0.2612
#Water Ice Cover       0.4001    -0.6194  0.9114       0.2612           1.0000

现在,我有了人口与各种土地覆盖类型之间的所有皮尔森“ r”相关值。

我现在要做的是计算多元线性回归。我正在尝试在以下表面覆盖的种群密度和面积百分比之间执行多元线性回归,并计算回归的R2:发达的,种植的/栽培的等级以及其他一些等级。也可以通过熊猫吗?

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用Scikit-learn或Statsmodels进行多元回归。

您可以在此处使用scikit_learn看到多元回归的一个示例:Multiple linear regression in Python

对于Statsmodels,您可以执行以下操作:

<div id="parent">
  <div id="son2"></div>
  <div id="son"></div>
</div>