-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPerf-improve.Rmd
474 lines (341 loc) · 13.3 KB
/
Perf-improve.Rmd
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# Improving performance
```{r Perf-improve-1, include = FALSE}
source("common.R")
```
Attaching the needed libraries:
```{r Perf-improve-2, warning=FALSE, message=FALSE}
library(ggplot2)
library(dplyr)
library(purrr)
```
## Exercises 24.3.1
**Q1.** What are faster alternatives to `lm()`? Which are specifically designed to work with larger datasets?
**A1.** Faster alternatives to `lm()` can be found by visiting [CRAN Task View: High-Performance and Parallel Computing with R](https://cran.r-project.org/web/views/HighPerformanceComputing.html) page.
Here are some of the available options:
- `speedglm::speedlm()` (for large datasets)
- `biglm::biglm()` (specifically designed for data too large to fit in memory)
- `RcppEigen::fastLm()` (using the `Eigen` linear algebra library)
High performances can be obtained with these packages especially if R is linked against an optimized BLAS, such as ATLAS. You can check this information using `sessionInfo()`:
```{r Perf-improve-3}
sessInfo <- sessionInfo()
sessInfo$matprod
sessInfo$LAPACK
```
Comparing performance of different alternatives:
```{r Perf-improve-4}
library(gapminder)
# having a look at the data
glimpse(gapminder)
bench::mark(
"lm" = stats::lm(lifeExp ~ continent * gdpPercap, gapminder),
"speedglm" = speedglm::speedlm(lifeExp ~ continent * gdpPercap, gapminder),
"biglm" = biglm::biglm(lifeExp ~ continent * gdpPercap, gapminder),
"fastLm" = RcppEigen::fastLm(lifeExp ~ continent * gdpPercap, gapminder),
check = FALSE,
iterations = 1000
)[1:5]
```
The results might change depending on the size of the dataset, with the performance benefits accruing bigger the dataset.
You will have to experiment with different algorithms and find the one that fits the needs of your dataset the best.
**Q2.** What package implements a version of `match()` that's faster for repeated look ups? How much faster is it?
**A2.** The package (and the respective function) is `fastmatch::fmatch()`^[In addition to Google search, you can also try [packagefinder](https://www.zuckarelli.de/packagefinder/tutorial.html) to search for CRAN packages.].
The documentation for this function notes:
> It is slightly faster than the built-in version because it uses more specialized code, but in addition it retains the hash table within the table object such that it can be re-used, dramatically reducing the look-up time especially for large table.
With a small vector, `fmatch()` is only slightly faster, but of the same order of magnitude.
```{r Perf-improve-5}
library(fastmatch, warn.conflicts = FALSE)
small_vec <- c("a", "b", "x", "m", "n", "y")
length(small_vec)
bench::mark(
"base" = match(c("x", "y"), small_vec),
"fastmatch" = fmatch(c("x", "y"), small_vec)
)[1:5]
```
But, with a larger vector, `fmatch()` is orders of magnitude faster! ⚡
```{r Perf-improve-6}
large_vec <- c(rep(c("a", "b"), 1e4), "x", rep(c("m", "n"), 1e6), "y")
length(large_vec)
bench::mark(
"base" = match(c("x", "y"), large_vec),
"fastmatch" = fmatch(c("x", "y"), large_vec)
)[1:5]
```
We can also look at the hash table:
```{r Perf-improve-7}
fmatch.hash(c("x", "y"), small_vec)
```
Additionally, `{fastmatch}` provides equivalent of the familiar infix operator:
```{r Perf-improve-8}
library(fastmatch)
small_vec <- c("a", "b", "x", "m", "n", "y")
c("x", "y") %in% small_vec
c("x", "y") %fin% small_vec
```
**Q3.** List four functions (not just those in base R) that convert a string into a date time object. What are their strengths and weaknesses?
**A3.** Here are four functions that convert a string into a date time object:
- `base::as.POSIXct()`
```{r Perf-improve-9}
base::as.POSIXct("2022-05-05 09:23:22")
```
- `base::as.POSIXlt()`
```{r Perf-improve-10}
base::as.POSIXlt("2022-05-05 09:23:22")
```
- `lubridate::ymd_hms()`
```{r Perf-improve-11}
lubridate::ymd_hms("2022-05-05-09-23-22")
```
- `fasttime::fastPOSIXct()`
```{r Perf-improve-12}
fasttime::fastPOSIXct("2022-05-05 09:23:22")
```
We can also compare their performance:
```{r Perf-improve-13}
bench::mark(
"as.POSIXct" = base::as.POSIXct("2022-05-05 09:23:22"),
"as.POSIXlt" = base::as.POSIXlt("2022-05-05 09:23:22"),
"ymd_hms" = lubridate::ymd_hms("2022-05-05-09-23-22"),
"fastPOSIXct" = fasttime::fastPOSIXct("2022-05-05 09:23:22"),
check = FALSE,
iterations = 1000
)
```
There are many more packages that implement a way to convert from string to a date time object. For more, see [CRAN Task View: Time Series Analysis](https://cran.r-project.org/web/views/TimeSeries.html)
**Q4.** Which packages provide the ability to compute a rolling mean?
**A4.** Here are a few packages and respective functions that provide a way to compute a rolling mean:
- `RcppRoll::roll_mean()`
- `data.table::frollmean()`
- `roll::roll_mean()`
- `zoo::rollmean()`
- `slider::slide_dbl()`
**Q5.** What are the alternatives to `optim()`?
**A5.** The `optim()` function provides general-purpose optimization. As noted in its docs:
> General-purpose optimization based on Nelder–Mead, quasi-Newton and conjugate-gradient algorithms. It includes an option for box-constrained optimization and simulated annealing.
There are many alternatives and the exact one you would want to choose would depend on the type of optimization you would like to do.
Most available options can be seen at [CRAN Task View: Optimization and Mathematical Programming](https://cran.r-project.org/web/views/Optimization.html).
## Exercises 24.4.3
**Q1.** What's the difference between `rowSums()` and `.rowSums()`?
**A1.** The documentation for these functions state:
> The versions with an initial dot in the name (.colSums() etc) are ‘bare-bones’ versions for use in programming: they apply only to numeric (like) matrices and do not name the result.
Looking at the source code,
- `rowSums()` function does a number of checks to validate if the arguments are acceptable
```{r Perf-improve-14}
rowSums
```
- `.rowSums()` directly proceeds to computation using an internal code which is built in to the R interpreter
```{r Perf-improve-15}
.rowSums
```
But they have comparable performance:
```{r Perf-improve-16}
x <- cbind(x1 = 3, x2 = c(4:1e4, 2:1e5))
bench::mark(
"rowSums" = rowSums(x),
".rowSums" = .rowSums(x, dim(x)[[1]], dim(x)[[2]])
)[1:5]
```
**Q2.** Make a faster version of `chisq.test()` that only computes the chi-square test statistic when the input is two numeric vectors with no missing values. You can try simplifying `chisq.test()` or by coding from the [mathematical definition](http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test).
**A2.** If the function is supposed to accept only two numeric vectors without missing values, then we can make `chisq.test()` do less work by removing code corresponding to the following :
- checks for data frame and matrix inputs
- goodness-of-fit test
- simulating *p*-values
- checking for missing values
This leaves us with a much simpler, bare bones implementation:
```{r Perf-improve-17}
my_chisq_test <- function(x, y) {
x <- table(x, y)
n <- sum(x)
nr <- as.integer(nrow(x))
nc <- as.integer(ncol(x))
sr <- rowSums(x)
sc <- colSums(x)
E <- outer(sr, sc, "*") / n
v <- function(r, c, n) c * r * (n - r) * (n - c) / n^3
V <- outer(sr, sc, v, n)
dimnames(E) <- dimnames(x)
STATISTIC <- sum((abs(x - E))^2 / E)
PARAMETER <- (nr - 1L) * (nc - 1L)
PVAL <- pchisq(STATISTIC, PARAMETER, lower.tail = FALSE)
names(STATISTIC) <- "X-squared"
names(PARAMETER) <- "df"
structure(
list(
statistic = STATISTIC,
parameter = PARAMETER,
p.value = PVAL,
method = "Pearson's Chi-squared test",
observed = x,
expected = E,
residuals = (x - E) / sqrt(E),
stdres = (x - E) / sqrt(V)
),
class = "htest"
)
}
```
And, indeed, this custom function performs slightly better^[Deliberately choosing a larger dataset to stress test the new function.] than its base equivalent:
```{r Perf-improve-18, warning=FALSE}
m <- c(rep("a", 1000), rep("b", 9000))
n <- c(rep(c("x", "y"), 5000))
bench::mark(
"base" = chisq.test(m, n)$statistic[[1]],
"custom" = my_chisq_test(m, n)$statistic[[1]]
)[1:5]
```
**Q3.** Can you make a faster version of `table()` for the case of an input of two integer vectors with no missing values? Can you use it to speed up your chi-square test?
**A3.** In order to make a leaner version of `table()`, we can take a similar approach and trim the unnecessary input checks in light of our new API of accepting just two vectors without missing values. We can remove the following components from the code:
- extracting data from objects entered in `...` argument
- dealing with missing values
- other input validation checks
In addition to this removal, we can also use `fastmatch::fmatch()` instead of `match()`:
```{r Perf-improve-19}
my_table <- function(x, y) {
x_sorted <- sort(unique(x))
y_sorted <- sort(unique(y))
x_length <- length(x_sorted)
y_length <- length(y_sorted)
bin <-
fastmatch::fmatch(x, x_sorted) +
x_length * fastmatch::fmatch(y, y_sorted) -
x_length
y <- tabulate(bin, x_length * y_length)
y <- array(
y,
dim = c(x_length, y_length),
dimnames = list(x = x_sorted, y = y_sorted)
)
class(y) <- "table"
y
}
```
The custom function indeed performs slightly better:
```{r Perf-improve-20}
x <- c(rep("a", 1000), rep("b", 9000))
y <- c(rep(c("x", "y"), 5000))
# `check = FALSE` because the custom function has an additional attribute:
# ".match.hash"
bench::mark(
"base" = table(x, y),
"custom" = my_table(x, y),
check = FALSE
)[1:5]
```
We can also use this function in our custom chi-squared test function and see if the performance improves any further:
```{r Perf-improve-21}
my_chisq_test2 <- function(x, y) {
x <- my_table(x, y)
n <- sum(x)
nr <- as.integer(nrow(x))
nc <- as.integer(ncol(x))
sr <- rowSums(x)
sc <- colSums(x)
E <- outer(sr, sc, "*") / n
v <- function(r, c, n) c * r * (n - r) * (n - c) / n^3
V <- outer(sr, sc, v, n)
dimnames(E) <- dimnames(x)
STATISTIC <- sum((abs(x - E))^2 / E)
PARAMETER <- (nr - 1L) * (nc - 1L)
PVAL <- pchisq(STATISTIC, PARAMETER, lower.tail = FALSE)
names(STATISTIC) <- "X-squared"
names(PARAMETER) <- "df"
structure(
list(
statistic = STATISTIC,
parameter = PARAMETER,
p.value = PVAL,
method = "Pearson's Chi-squared test",
observed = x,
expected = E,
residuals = (x - E) / sqrt(E),
stdres = (x - E) / sqrt(V)
),
class = "htest"
)
}
```
And, indeed, this new version of the custom function performs even better than it previously did:
```{r Perf-improve-22, warning=FALSE}
m <- c(rep("a", 1000), rep("b", 9000))
n <- c(rep(c("x", "y"), 5000))
bench::mark(
"base" = chisq.test(m, n)$statistic[[1]],
"custom" = my_chisq_test2(m, n)$statistic[[1]]
)[1:5]
```
## Exercises 24.5.1
**Q1.** The density functions, e.g., `dnorm()`, have a common interface. Which arguments are vectorised over? What does `rnorm(10, mean = 10:1)` do?
**A1.** The density function family has the following interface:
```{r Perf-improve-23, eval=FALSE}
dnorm(x, mean = 0, sd = 1, log = FALSE)
pnorm(q, mean = 0, sd = 1, lower.tail = TRUE, log.p = FALSE)
qnorm(p, mean = 0, sd = 1, lower.tail = TRUE, log.p = FALSE)
rnorm(n, mean = 0, sd = 1)
```
Reading the documentation reveals that the following parameters are vectorized:
`x`, `q`, `p`, `mean`, `sd`.
This means that something like the following will work:
```{r Perf-improve-24}
rnorm(c(1, 2, 3), mean = c(0, -1, 5))
```
But, for functions that don't have multiple vectorized parameters, it won't. For example,
```{r Perf-improve-25, error=TRUE}
pnorm(c(1, 2, 3), mean = c(0, -1, 5), log.p = c(FALSE, TRUE, TRUE))
```
The following function call generates 10 random numbers (since `n = 10`) with 10 different distributions with means supplied by the vector `10:1`.
```{r Perf-improve-26}
rnorm(n = 10, mean = 10:1)
```
**Q2.** Compare the speed of `apply(x, 1, sum)` with `rowSums(x)` for varying sizes of `x`.
**A2.** We can write a custom function to vary number of rows in a matrix and extract a data frame comparing performance of these two functions.
```{r Perf-improve-27, warning=FALSE}
benc_perform <- function(nRow, nCol = 100) {
x <- matrix(data = rnorm(nRow * nCol), nrow = nRow, ncol = nCol)
bench::mark(
rowSums(x),
apply(x, 1, sum)
)[1:5]
}
nRowList <- list(10, 100, 500, 1000, 5000, 10000, 50000, 100000)
names(nRowList) <- as.character(nRowList)
benchDF <- map_dfr(
.x = nRowList,
.f = ~ benc_perform(.x),
.id = "nRows"
) %>%
mutate(nRows = as.numeric(nRows))
```
Plotting this data reveals that `rowSums(x)` has *O*(1) behavior, while *O*(n) behavior.
```{r Perf-improve-28}
ggplot(
benchDF,
aes(
x = as.numeric(nRows),
y = median,
group = as.character(expression),
color = as.character(expression)
)
) +
geom_point() +
geom_line() +
labs(
x = "Number of Rows",
y = "Median Execution Time",
colour = "Function used"
)
```
**Q3.** How can you use `crossprod()` to compute a weighted sum? How much faster is it than the naive `sum(x * w)`?
**A3.** Both of these functions provide a way to compute a weighted sum:
```{r Perf-improve-29}
x <- c(1:6, 2, 3)
w <- rnorm(length(x))
crossprod(x, w)[[1]]
sum(x * w)[[1]]
```
But benchmarking their performance reveals that the latter is significantly faster than the former!
```{r Perf-improve-30}
bench::mark(
crossprod(x, w)[[1]],
sum(x * w)[[1]],
iterations = 1e6
)[1:5]
```