1

我使用 tidymodels 框架拟合多项逻辑回归模型来预测 iris 数据集中的物种。

library(tidymodels)

iris.lr = multinom_reg(
  mode="classification",
  penalty=NULL,
  mixture=NULL
) %>%
  set_engine("glmnet")

iris.fit = iris.lr %>%
  fit(Species ~. , data = iris)

然后我想看看我的模型的系数并写出公式。我的理解是我应该从 iris.fit 得到这个。

iris.fit 的输出有一个包含 Df、%Dev、Lambda 的 100 行表。iris 数据集只有 4 个预测变量。如何将此输出转换为系数?

4

2 回答 2

5

tidy()您可以使用该函数在数据框中获取所有系数(对于每个测试的 lambda) 。

library(tidymodels)
#> ── Attaching packages ────────────────────────────────────────── tidymodels 0.1.0 ──
#> ✓ broom     0.5.6      ✓ recipes   0.1.12
#> ✓ dials     0.0.6      ✓ rsample   0.0.6 
#> ✓ dplyr     0.8.5      ✓ tibble    3.0.1 
#> ✓ ggplot2   3.3.0      ✓ tune      0.1.0 
#> ✓ infer     0.5.1      ✓ workflows 0.1.1 
#> ✓ parsnip   0.1.1      ✓ yardstick 0.0.6 
#> ✓ purrr     0.3.4
#> ── Conflicts ───────────────────────────────────────────── tidymodels_conflicts() ──
#> x purrr::discard()  masks scales::discard()
#> x dplyr::filter()   masks stats::filter()
#> x dplyr::lag()      masks stats::lag()
#> x ggplot2::margin() masks dials::margin()
#> x recipes::step()   masks stats::step()

iris_lr <- multinom_reg(
  mode = "classification",
  penalty = NULL,
  mixture = NULL
) %>%
  set_engine("glmnet")

iris_fit = iris_lr %>%
  fit(Species ~ . , data = iris)

library(broom)

tidy(iris_fit)
#> # A tibble: 839 x 6
#>    class      term            step  estimate lambda dev.ratio
#>    <chr>      <chr>          <dbl>     <dbl>  <dbl>     <dbl>
#>  1 setosa     ""                 1  6.41e-16  0.435 -1.21e-15
#>  2 versicolor ""                 1 -1.62e-15  0.435 -1.21e-15
#>  3 virginica  ""                 1  9.81e-16  0.435 -1.21e-15
#>  4 setosa     ""                 2  2.44e- 1  0.396  6.56e- 2
#>  5 setosa     "Petal.Length"     2 -9.85e- 2  0.396  6.56e- 2
#>  6 versicolor ""                 2 -1.22e- 1  0.396  6.56e- 2
#>  7 virginica  ""                 2 -1.22e- 1  0.396  6.56e- 2
#>  8 setosa     ""                 3  4.62e- 1  0.361  1.20e- 1
#>  9 setosa     "Petal.Length"     3 -1.89e- 1  0.361  1.20e- 1
#> 10 versicolor ""                 3 -2.31e- 1  0.361  1.20e- 1
#> # … with 829 more rows

reprex 包(v0.3.0)于 2020-05-14 创建

于 2020-05-15T03:16:30.023 回答
1

系数如下:

    names(iris.fit$fit$beta)
[1] "setosa"     "versicolor" "virginica"

iris.fit$fit$beta$setosa
4 x 100 sparse Matrix of class "dgCMatrix"
   [[ suppressing 100 column names ‘s0’, ‘s1’, ‘s2’ ... ]]

Sepal.Length .  .           .          .          .          .        
Sepal.Width  .  .           .          .          .          .        
Petal.Length . -0.09849722 -0.1890163 -0.2737859 -0.3542876 -0.4108527
Petal.Width  .  .           .          .          .          .  

每个测试的 lambda 一列(iris.fit$fit$lambda)。您可以查看本教程中的 glmnet ,没有专门讨论多项式的部分,但其中解释了很多输出。

于 2020-05-11T09:46:25.260 回答