将模型拟合到 Python 中的所有变量 (Scikit Learn)

114*_*114 5 python r machine-learning scikit-learn

有人在其他地方询问过不同的包,但是在 Scikit Learn 中是否有一种方法可以包含所有变量或所有变量减去一些指定的数字,就像在 R 中一样?

举个例子来说明我的意思,假设我有一个回归 y = x1 + x2 + x3 + x4。在 RI 中,可以通过运行以下命令来评估此回归:

result = lm(y ~ ., data=DF)
summary(result)
Run Code Online (Sandbox Code Playgroud)

我不得不想象在 Python 中也有一种类似的方法来压缩公式,因为为更大的数据集写出所有变量有点愚蠢。

San*_*Dey 0

我们可以尝试以下解决方法(让我们使用iris数据集和标签species作为数字并拟合线性回归模型,以了解如何使用R和中的所有独立预测变量python sklearn):

在R中

summary(lm(as.numeric(Species)~., iris))[c('coefficients', 'r.squared')]

$coefficients
                Estimate Std. Error   t value     Pr(>|t|)
(Intercept)   1.18649525 0.20484104  5.792273 4.150495e-08
Sepal.Length -0.11190585 0.05764674 -1.941235 5.416918e-02
Sepal.Width  -0.04007949 0.05968881 -0.671474 5.029869e-01
Petal.Length  0.22864503 0.05685036  4.021874 9.255215e-05
Petal.Width   0.60925205 0.09445750  6.450013 1.564180e-09

$r.squared
[1] 0.9303939
Run Code Online (Sandbox Code Playgroud)

在 Python 中(sklearn 和 Pasty)

from sklearn.datasets import load_iris
import pandas as pd
from patsy import dmatrices

iris = load_iris()
names = [f_name.replace(" ", "_").strip("_(cm)") for f_name in iris.feature_names]
iris_df = pd.DataFrame(iris.data, columns=names)
iris_df['species'] = iris.target

# pasty does not support '.' at least in windows python 2.7, so here is the workaround 
y, X = dmatrices('species ~ ' + '+'.join(iris_df.columns - ['species']),
                  iris_df, return_type="dataframe")

from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X, y)

print model.score(X,y)
# 0.930422367533

print model.intercept_, model.coef_
# [ 0.19208399] [[0.22700138  0.60989412 -0.10974146 -0.04424045]]
Run Code Online (Sandbox Code Playgroud)

R正如我们所看到的,在和Python中学习的模型pasty是相似的(系数的顺序不同)。