/
methodFeature.R
195 lines (173 loc) · 5.59 KB
/
methodFeature.R
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
#' @include modelPartition.R
#' @name interface-featureBased
#' @rdname interface-featureBased
#' @title featureBased interface
#' @seealso [lcMethodFeature] [lcMethodGCKM] [lcMethodLMKM]
#' @keywords internal
NULL
setClass('lcMethodFeature', contains = 'lcMethod')
setValidity('lcMethodFeature', function(object) {
assert_that(has_lcMethod_args(object, formalArgs(lcMethodFeature)))
assert_that(
!isArgDefined(object, 'representationStep') ||
is.function(object$representationStep) ||
is.matrix(object$representationStep)
)
assert_that(
!isArgDefined(object, 'clusterStep') || is.function(object$clusterStep)
)
})
#' @export
#' @title Feature-based clustering
#' @description Feature-based clustering.
#' @inheritParams lcModelPartition
#' @param representationStep A `function` with signature `function(method, data)` that computes the representation per strata, returned as a `matrix`.
#' Alternatively, `representationStep` is a pre-computed representation `matrix`.
#' @param clusterStep A `function` with signature `function(repdata)` that outputs a `lcModel`.
#' @param standardize A `function` to standardize the output `matrix` of the representation step. By default, the output is shifted and rescaled to ensure zero mean and unit variance.
#' @param ... Additional arguments.
#' @section Linear regresion & k-means example:
#' In this example we define a feature-based approach where each trajectory is represented using a linear regression model.
#' The coefficients of the trajectories are then clustered using k-means.
#'
#' Note that this method is already implemented as [lcMethodLMKM()].
#'
#' Representation step:
#' \preformatted{
#' repStep <- function(method, data, verbose) {
#' library(data.table)
#' library(magrittr)
#' xdata = as.data.table(data)
#' coefdata <- xdata[,
#' lm(method$formula, .SD) %>% coef() %>% as.list(),
#' keyby = c(method$id)
#' ]
#' # exclude the id column
#' coefmat <- subset(coefdata, select = -1) %>% as.matrix()
#' rownames(coefmat) <- coefdata[[method$id]]
#' return(coefmat)
#' }
#' }
#'
#' Cluster step:
#' \preformatted{
#' clusStep <- function(method, data, repMat, envir, verbose) {
#' km <- kmeans(repMat, centers = method$nClusters)
#'
#' lcModelPartition(
#' response = method$response,
#' data = data,
#' trajectoryAssignments = km$cluster
#' )
#' }
#' }
#'
#' Now specify the method and fit the model:
#' \preformatted{
#' data(latrendData)
#' method <- lcMethodFeature(
#' formula = Y ~ Time,
#' response = "Y",
#' id = "Id",
#' time = "Time",
#' representationStep = repStep,
#' clusterStep = clusStep
#'
#' model <- latrend(method, data = latrendData)
#' )
#' }
#'
#' @family lcMethod implementations
lcMethodFeature = function(
response,
representationStep,
clusterStep,
standardize = scale,
center = meanNA,
time = getOption('latrend.time'),
id = getOption('latrend.id'),
...
) {
mc = match.call.all()
mc$Class = 'lcMethodFeature'
do.call(new, as.list(mc))
}
#' @rdname interface-featureBased
setMethod('getArgumentDefaults', 'lcMethodFeature', function(object) {
c(
formals(lcMethodFeature),
callNextMethod()
)
})
#' @rdname interface-featureBased
#' @inheritParams getName
setMethod('getName', 'lcMethodFeature', function(object) 'two-step clustering')
#' @rdname interface-featureBased
setMethod('getShortName', 'lcMethodFeature', function(object) 'twostep')
#' @rdname interface-featureBased
setMethod('prepareData', 'lcMethodFeature', function(method, data, verbose, ...) {
assert_that(has_name(data, responseVariable(method)))
callNextMethod()
})
#' @rdname interface-featureBased
#' @inheritParams fit
setMethod('fit', 'lcMethodFeature', function(method, data, envir, verbose, ...) {
nIds = uniqueN(data[[idVariable(method)]])
## Representation step #
rstep = method$representationStep
if (is.function(rstep)) {
repOut = rstep(method, data, verbose)
} else {
repOut = rstep
}
if (is.environment(repOut)) {
repEnv = repOut
} else if (is.list(repOut)) {
repEnv = list2env(repOut)
} else if (is.matrix(repOut)) {
repEnv = new.env()
repEnv$repMat = repOut
} else {
stop('unexpected output from the representationStep function. See the documentation ?lcMethodFeature for help.')
}
assert_that(exists('repMat', envir = repEnv))
assert_that(is.matrix(repEnv$repMat), msg = 'invalid class output from the representation step. Expected "repMat" to be a matrix.')
assert_that(nrow(repEnv$repMat) == nIds, msg = 'invalid output from the representation step; expected "repMat" to be a matrix with one row per id.')
assert_that(ncol(repEnv$repMat) >= 1)
repEnv$repMat = standardizeTrajectoryCoefMatrix(repEnv$repMat, method$standardize)
## Cluster step #
model = method$clusterStep(
method = method,
data = data,
repMat = repEnv$repMat,
envir = repEnv,
verbose = verbose
)
assert_that(
is.lcModel(model),
msg = 'invalid output from the clusterStep function; expected object of class lcModel. See the documentation of ?lcMethodFeature for help.'
)
model@data = data
model@call = getCall(method) # will be updated by latrend
model@method = method
model
})
standardizeTrajectoryCoefMatrix = function(x, fun) {
assert_that(is.matrix(x))
if (is.function(fun)) {
newx = fun(x)
assert_that(
is.matrix(newx),
nrow(newx) == nrow(x),
ncol(newx) == ncol(x),
msg = 'standardize function changed dimensions of the input matrix'
)
return(newx)
} else if (isTRUE(fun)) {
scale(x)
} else if (isFALSE(fun)) {
x
} else {
stop('unsupported value for standardize')
}
}