在Python(Scikit Learn)中将模型适配于所有变量

4

这个问题在其他地方有人问到过,但是在Scikit Learn中是否有一种方法可以包括所有变量或减去某些指定数量的所有变量,就像在R中一样?

举个例子,假设我有一个回归 y = x1 + x2 + x3 + x4。在R中,我可以通过运行以下命令来评估这个回归:

result = lm(y ~ ., data=DF)
summary(result)

我想必须有一种类似的方法可以在Python中压缩公式,因为为更大的数据集编写所有变量有点愚蠢。


1
我不这么认为。这里有一个sklearn的例子在这里 - cdeterman
@114 你具体在做什么?能给一个玩具示例吗? - juanpa.arrivillaga
@juanpa.arrivillaga,目前我没有遇到上述问题的数据集,但是我可以轻松地想象出一个包含20000行和200个特征的CSV文件,在输入每个变量名称时会非常繁琐。我想在Python中进行此操作的方法是使用pandas获取列表,使用类似于“list(my_dataframe.columns.values)”的语句,并将其传递给模型以实现某种程度的自动化。 - 114
你使用my_dataframe.values,而Sklearn通常需要某种形式的numpy矩阵。再给我一个你正在做的例子,因为我使用过R和sklearn,从来没有感觉到缺少R中的“公式”。我认为 statsmodels如果你喜欢公式进行回归分析,可以使用statsmodels - juanpa.arrivillaga
@juanpa.arrivillaga 我犯了错误。那么我更新后的问题就是,将该列表作为依赖变量的列表输入Scikit模型的最佳方法是什么? - 114
显示剩余3条评论
2个回答

2
有没有一种方法在Scikit Learn中包含所有变量或排除某些指定数量的变量?
是的,使用sklearn + pandas,要使用除一个变量之外的所有变量进行拟合,并将该变量用作标签,您可以简单地执行以下操作。
model.fit(df.drop('y', axis=1), df['y'])

这对大多数sklearn模型都适用。

如果不使用pasty,这将是R中~-符号的pandas+sklearn等效表示。

要排除多个变量,可以执行以下操作

df.drop(['v1', 'v2'], axis=1)

0
我们可以尝试以下解决方法(使用iris数据集和标签species作为数字,并拟合线性回归模型,以查看如何在Rpython 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

在Python中(使用pasty的sklearn)

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]]

正如我们所看到的,用pastyRPython中学习的模型是相似的(系数的顺序不同)。


1
statsmodels原生支持patsy公式...值得一提...http://statsmodels.sourceforge.net/0.6.0/examples/notebooks/generated/formulas.html - juanpa.arrivillaga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接