File: ResampleInstances.R

package info (click to toggle)
r-cran-mlr 2.19.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,264 kB
  • sloc: ansic: 65; sh: 13; makefile: 5
file content (132 lines) | stat: -rw-r--r-- 5,909 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
instantiateResampleInstance = function(desc, size, task = NULL, coords) {
  UseMethod("instantiateResampleInstance")
}

instantiateResampleInstance.HoldoutDesc = function(desc, size, task = NULL, coords) {
  inds = sample(size, size * desc$split)
  makeResampleInstanceInternal(desc, size, train.inds = list(inds))
}

instantiateResampleInstance.CVDesc = function(desc, size, task = NULL, coords) {
  # Random sampling CV
  if (!desc$fixed) {
    if (desc$iters > size) {
      stopf("Cannot use more folds (%i) than size (%i)!", desc$iters, size)
    }
    test.inds = chunk(seq_len(size), shuffle = TRUE, n.chunks = desc$iters)
    makeResampleInstanceInternal(desc, size, test.inds = test.inds)
  } else {

    # CV with only predefined indices ("fixed")

    if (is.null(task$blocking)) {
      stopf("To use blocking in resampling, you need to pass a factor variable when creating the task!")
    }

    # In the inner call, the implementation is able to adapt by automatically reducing one level (see line if (0 %in% length.test.inds)).
    # So having always `length(iters) = length(levels(task$blocking)` is the most safe environment for the function to work.
    if (desc$iters != length(levels(task$blocking))) {
      desc$iters = length(levels(task$blocking))
      warningf("Adjusting levels to match number of blocking levels.")
    }
    levs = levels(task$blocking)
    n.levels = length(levs)

    # Why do we need the helper desc? If we would call 'instantiateResampleInstance()' here,
    # we would call the function within itself and will receive an 'error-c-stack-usage-is-too-close-to-the-limit' error
    # So we simply change the class name to mimic a new function..
    attr(desc, "class")[1] = "CVHelperDesc"
    # create fake ResampleInstance
    inst = instantiateResampleInstance(desc, n.levels, task)
    attr(desc, "class")[1] = "CVDesc"

    # now exchange block indices with indices of elements of this block and shuffle
    test.inds = lapply(inst$test.inds, function(i) which(task$blocking %in% levs[i]))

    # Nested resampling: We need to create a list with length(levels) first.
    # Then one fold will be length(0) because we are missing one factor level because we are in the inner level
    # We check for this and remove this fold
    # There is no other way to do this. If we initially set "desc$iters" to length(levels) - 1, test.inds will not be created correctly
    length.test.inds = unlist(lapply(test.inds, function(x) length(x)))
    if (0 %in% length.test.inds) {
      index = match(0, length.test.inds)
      test.inds[[index]] = NULL
      size = length(task$env$data[, 1])
      desc$iters = length(test.inds)
    }
    makeResampleInstanceInternal(desc, size, test.inds = test.inds)
  }
}

instantiateResampleInstance.SpCVDesc = function(desc, size, task = NULL, coords) {

  if (is.null(task)) {
    stopf("Please provide a task.")
  }
  if (is.null(task$coordinates)) {
    stopf("Please provide suitable coordinates for SpCV. See ?Task for help.")
  }
  # perform kmeans clustering
  inds = kmeans(task$coordinates, centers = desc$iters)
  inds = factor(inds$cluster)

  # uses resulting factor levels from kmeans clustering to set up a list of
  # length x (x = folds) with row indices of the data referring to which fold
  # each observations is assigned to
  test.inds = lapply(levels(inds), function(x, spl) {
    which(spl == x)
  }, spl = inds)

  makeResampleInstanceInternal(desc, size, test.inds = test.inds)
}

instantiateResampleInstance.LOODesc = function(desc, size, task = NULL, coords) {
  desc$iters = size
  makeResampleInstanceInternal(desc, size, test.inds = as.list(seq_len(size)))
}

instantiateResampleInstance.SubsampleDesc = function(desc, size, task = NULL, coords) {
  inds = lapply(seq_len(desc$iters), function(x) sample(size, size * desc$split))
  makeResampleInstanceInternal(desc, size, train.inds = inds)
}

instantiateResampleInstance.BootstrapDesc = function(desc, size, task = NULL, coords) {
  inds = lapply(seq_len(desc$iters), function(x) sample(size, size, replace = TRUE))
  makeResampleInstanceInternal(desc, size, train.inds = inds)
}

instantiateResampleInstance.RepCVDesc = function(desc, size, task = NULL, coords) {
  folds = desc$iters / desc$reps
  d = makeResampleDesc("CV", iters = folds, blocking.cv = desc$blocking.cv, fixed = desc$fixed)
  i = replicate(desc$reps, makeResampleInstance(d, size = size), simplify = FALSE)
  train.inds = Reduce(c, lapply(i, function(j) j$train.inds))
  test.inds = Reduce(c, lapply(i, function(j) j$test.inds))
  g = as.factor(rep(seq_len(desc$reps), each = folds))
  makeResampleInstanceInternal(desc, size, train.inds = train.inds, test.inds = test.inds, group = g)
}

instantiateResampleInstance.SpRepCVDesc = function(desc, size, task = NULL, coords) {
  folds = desc$iters / desc$reps
  d = makeResampleDesc("SpCV", iters = folds)
  i = replicate(desc$reps, makeResampleInstance(d, task = task), simplify = FALSE)
  train.inds = Reduce(c, lapply(i, function(j) j$train.inds))
  test.inds = Reduce(c, lapply(i, function(j) j$test.inds))
  g = as.factor(rep(seq_len(desc$reps), each = folds))
  makeResampleInstanceInternal(desc, size, train.inds = train.inds, test.inds = test.inds, group = g)
}

instantiateResampleInstance.FixedWindowCVDesc = function(desc, size, task = NULL, coords) {
  makeResamplingWindow(desc, size, task, coords, "FixedWindowCV")
}

instantiateResampleInstance.GrowingWindowCVDesc = function(desc, size, task = NULL, coords) {
  makeResamplingWindow(desc, size, task, coords, "GrowingWindowCV")
}

instantiateResampleInstance.CVHelperDesc = function(desc, size, task = NULL, coords) {
  if (desc$iters > size) {
    stopf("Cannot use more folds (%i) than size (%i)!", desc$iters, size)
  }
  test.inds = chunk(seq_len(size), shuffle = TRUE, n.chunks = desc$iters)
  makeResampleInstanceInternal(desc, size, test.inds = test.inds)
}