【问题标题】:Fit model to all variables in Python (Scikit Learn)将模型拟合到 Python 中的所有变量(Scikit Learn)
【发布时间】:2017-07-13 03:08:47
【问题描述】:

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

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

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

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

【问题讨论】:

  • 我不相信,这里有一个sklearn的例子here
  • @lmo 我将其标记为两者,因为我认为 R 用户和 Scikit 用户之间可能存在重叠。
  • @114 你到底在做什么?你能举个玩具的例子吗?
  • @juanpa.arrivillaga 我现在实际上没有遇到上述问题的数据集,但我可以很容易地想象一个具有 20000 行和 200 个特征的 csv,其中输入每个变量名称会非常乏味。我想在 Python 中做到这一点的方法是使用 pandas 来获取一个使用类似 list(my_dataframe.columns.values) 的列表并以某种方式将其输入到模型中?
  • 没有。你使用my_dataframe.values Sklearn 通常期望某种numpy 矩阵。再一次,给我一个你在做什么的例子,因为我用过 R 和 sklearn,而且我从来没有真正错过 R 的“公式”。我认为 statsmodels. If you like formulas, for regression, you can use [statsmodels`](statsmodels.sourceforge.net/0.6.0/examples/notebooks/generated/…)

标签: python r machine-learning scikit-learn


【解决方案1】:

我们可以尝试以下解决方法(让我们使用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 中(带有糊状的 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]]

我们可以看到RPythonpasty学习的模型是相似的(系数的顺序不同)。

【讨论】:

【解决方案2】:

Scikit Learn 中有没有一种方法可以包含所有变量或所有变量减去某个指定的数字?

是的,使用 sklearn + pandas,以适应使用除一个变量之外的所有变量,并使用该变量作为标签,您可以简单地做

model.fit(df.drop('y', axis=1), df['y'])

这适用于大多数sklearn 模型。

这将是 pandas+sklearn 等效于 R 的 ~- 表示法,如果不使用 pasty

要排除多个变量,可以这样做

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

【讨论】:

    猜你喜欢
    • 2021-05-09
    • 2013-04-25
    • 2014-01-07
    • 2019-08-18
    • 2015-12-01
    • 2017-02-24
    • 2021-06-09
    • 2016-11-26
    • 1970-01-01
    相关资源
    最近更新 更多