4

我想比较使用相同预测变量但模型参数不同的一堆模型的模型性能。这似乎是broom用来创建整洁输出的地方,但我想不通。这是一些无效的代码,有助于建议我在想什么:

seq(1:10) %>%
do(fit = knn(train_Market, test_Market, train_Direction, k=.), score = mean(fit==test_Direction)) %>%
tidy()

有关更多上下文,这是我们正在尝试 tidyverse-ify 的 ISLR 实验室之一的一部分。你可以在这里看到整个实验室:https ://github.com/AmeliaMN/tidy-islr/blob/master/lab3/lab3.Rmd

[更新:可重现的示例] 由于需要在模型拟合之前进行数据整理,因此很难在这里制作一个最小的示例,但这应该是可重现的:

library(ISLR)
library(dplyr)

train = Smarket %>%
  filter(Year < 2005)
test = Smarket %>%
  filter(Year >= 2005)

train_Market = train %>%
  select(Lag1, Lag2)
test_Market = test %>%
  select(Lag1, Lag2)

train_Direction = train %>%
  select(Direction) %>%
  .$Direction 

set.seed(1)
knn_pred = knn(train_Market, test_Market, train_Direction, k=1)
mean(knn_pred==test_Direction)

knn_pred = knn(train_Market, test_Market, train_Direction, k=3)
mean(knn_pred==test_Direction)

knn_pred = knn(train_Market, test_Market, train_Direction, k=4)
mean(knn_pred==test_Direction)

等等

4

1 回答 1

3

由于每个 knn(和 oracle)的输出都是一个向量,因此这是 tidyr 的一个很好的例子unnest(结合 purrrmaprep_along:

library(class)
library(purrr)
library(tidyr)
set.seed(1)

predictions <- data_frame(k = 1:5) %>%
  unnest(prediction = map(k, ~ knn(train_Market, test_Market, train_Direction, k = .))) %>%
  mutate(oracle = rep_along(prediction, test_Direction))

然后将predictions变量组织为:

# A tibble: 1,260 x 3
       k prediction oracle
   <int>     <fctr> <fctr>
1      1         Up     Up
2      1       Down     Up
3      1         Up   Down
4      1         Up     Up
5      1         Up     Up
6      1       Down     Up
7      1       Down   Down
8      1       Down     Up
9      1       Down     Up
10     1         Up     Up
# ... with 1,250 more rows

可以很容易地总结:

predictions %>%
  group_by(k) %>%
  summarize(accuracy = mean(prediction == oracle))

同样,您不需要扫帚,因为每个输出都是一个因素,但如果它是一个模型,您可以使用扫帚tidyaugment然后以类似的方式将其取消嵌套。


这种方法的一个重要方面是它对许多参数组合很灵活,通过将它们与 tidyr crossing(或expand.grid)组合并使用invoke_rows将函数应用于每一行。例如,您可以尝试以下的变lk

crossing(k = 2:5, l = 0:1) %>%
  invoke_rows(knn, ., train = train_Market, test = test_Market, cl = train_Direction) %>%
  unnest(prediction = .out) %>%
  mutate(oracle = rep_along(prediction, test_Direction)) %>%
  group_by(k, l) %>%
  summarize(accuracy = mean(prediction == oracle))

这将返回:

Source: local data frame [8 x 3]
Groups: k [?]

      k     l  accuracy
  <int> <int>     <dbl>
1     2     0 0.5396825
2     2     1 0.5277778
3     3     0 0.5317460
4     3     1 0.5317460
5     4     0 0.5277778
6     4     1 0.5357143
7     5     0 0.4841270
8     5     1 0.4841270
于 2016-09-16T17:21:07.130 回答