首页 > 解决方案 > 如何使用 scikit-learn 对 python 中的数据集执行多元线性回归?

问题描述

我的 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},

...
]

然后将该代码放入熊猫对象中:

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 

然后得到 pearson '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

现在我有了人口和各种土地覆盖类型之间的所有 pearson 'r' 相关值。

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

谢谢

标签: pythonpandasscikit-learnlinear-regression

解决方案


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

您可以在此处查看使用 scikit_learn 的多元回归示例:Python 中的多元线性回归

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

import statsmodels.api as sm    

X = df[[“variable_1”, “variable_2”]]
y = df[“target”]

model = sm.OLS(y, X).fit()
predictions = model.predict(X)
model.summary()

推荐阅读