Last updated: 2019-10-05

Checks: 6 1

Knit directory: ebpmf_demo/

This reproducible R Markdown analysis was created with workflowr (version 1.4.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


The R Markdown file has unstaged changes. To know which version of the R Markdown file created these results, you’ll want to first commit it to the Git repo. If you’re still working on the analysis, you can ignore this warning. When you’re finished, you can run wflow_publish to commit the R Markdown file and build the HTML.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20190923) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility. The version displayed above was the version of the Git repository at the time these results were generated.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/

Untracked files:
    Untracked:  analysis/.ipynb_checkpoints/
    Untracked:  analysis/ebpmf_demo.Rmd
    Untracked:  analysis/ebpmf_rankk_demo2.Rmd
    Untracked:  analysis/softmax_experiments.ipynb
    Untracked:  docs/figure/test.Rmd/

Unstaged changes:
    Modified:   analysis/ebpmf_rankk_demo.Rmd
    Modified:   analysis/softmax_experiments.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the R Markdown and HTML files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view them.

File Version Author Date Message
html a2aeadb zihao12 2019-10-02 Build site.
Rmd 15e4e99 zihao12 2019-10-02 experiment with softmax in r

Goal

I need to compute softmax along an axis in 3d array (see equation below), but it often takes too long for a moderately sized array.

\[ \begin{align} \frac{exp(X_{ijk})}{\sum_k exp(X_{ijk})} \end{align} \]

## x is 3d array, and we want to do softmax along the 3rd axis, so sum_k prob_ijk = 1
softmax <- function(x){
  score.exp <- exp(x)
  probs <-sweep(score.exp, MARGIN = c(1,2), apply(score.exp, MARGIN = c(1,2), sum), '/')
  return(probs)
}

# n = 1000
# p = 5000
# k = 10
# x = array(runif(n*p*k), dim = c(n, p,k)) ## this step also takes a long time!!
# start = proc.time()
# x.softmax = softmax(x)
# runtime = proc.time() - start
# print(runtime[[3]])
## [1] 12.928
# x.softmax.sum =  apply(x.softmax, MARGIN = c(1,2), sum)
# print(all.equal(x.softmax.sum, matrix(replicate(n*p, 1), nrow = n)))
## TRUE

Here is how scipy implements it: np.exp(x - logsumexp(x, axis=axis, keepdims=True))

So do that in the log space first:

\[ \begin{align} exp(X_{ijk} - \sum_k logsumexp(X_{ijk})) \end{align} \]

library(matrixStats)
softmax2 <- function(x){
  k = dim(x)[3]
  x.logsumexp = apply(x, c(1,2), logSumExp)
  x.softmax = exp(x - replicate(k, x.logsumexp))
  return(x.softmax)
}
# n = 1000
# p = 5000
# k = 10
# x = array(runif(n*p*k), dim = c(n, p,k)) ## this step also takes a long time!!
# start = proc.time()
# x.softmax = softmax2(x)
# runtime = proc.time() - start
# print(runtime[[3]])
## [1] 16.445
# x.softmax.sum =  apply(x.softmax, MARGIN = c(1,2), sum)
# print(all.equal(x.softmax.sum, matrix(replicate(n*p, 1), nrow = n)))
## [1] TRUE

It is even slower. Python code is around 1.88 seconds.

From Matthew:

softmax <- function(x){
  score.exp <- exp(x)
  probs <-sweep(score.exp, MARGIN = c(1,2), apply(score.exp, MARGIN = c(1,2), sum), '/')
  return(probs)
}
softmax2 <- function(x){
  score.exp <- exp(x)
  probs <-sweep(score.exp, MARGIN = c(1,2), rowSums(score.exp,dims=2), '/')
  return(probs)
}
softmax3 <- function(x){
  score.exp <- exp(x)
  probs <-as.vector(score.exp)/as.vector(rowSums(score.exp,dims=2))
  dim(probs) <- dim(x)
  return(probs)
}
# n = 1000
# p = 5000
# k = 10
# x = array(runif(n*p*k), dim = c(n, p,k)) ## this step also takes a long time!!
# start = proc.time()
# x.softmax = softmax(x)
# runtime = proc.time() - start
# print(runtime[[3]])
# start = proc.time()
# x.softmax2 = softmax2(x)
# runtime = proc.time() - start
# print(runtime[[3]])
# start = proc.time()
# x.softmax3 = softmax3(x)
# runtime = proc.time() - start
# print(runtime[[3]])
# identical(x.softmax3,x.softmax)
# identical(x.softmax2,x.softmax)
# 
# # [1] 11.188
# # [1] 2.662
# # [1] 1.685
# # [1] TRUE
# # [1] TRUE


n = 100
p = 200
k = 2
x = array(runif(n*p*k), dim = c(n, p,k)) ## this step also takes a long time!!
start = proc.time()
x.softmax = softmax(x)
runtime = proc.time() - start
print(runtime[[3]])
[1] 0.027
start = proc.time()
x.softmax2 = softmax2(x)
runtime = proc.time() - start
print(runtime[[3]])
[1] 0.01
start = proc.time()
x.softmax3 = softmax3(x)
runtime = proc.time() - start
print(runtime[[3]])
[1] 0.004
identical(x.softmax3,x.softmax)
[1] TRUE
identical(x.softmax2,x.softmax)
[1] TRUE

Lesson

  • try to avoid “apply”: rowSums(score.exp,dims=2) is much faster than apply(score.exp, MARGIN = c(1,2), sum)
  • R is column major, so be aware of what as.vector does
  • operations between vectors of different lengths: shorter vectors are recycled until it matches the lengths of the longer vector

sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS  10.14

Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] matrixStats_0.54.0

loaded via a namespace (and not attached):
 [1] workflowr_1.4.0 Rcpp_1.0.2      digest_0.6.21   rprojroot_1.3-2
 [5] backports_1.1.5 git2r_0.25.2    magrittr_1.5    evaluate_0.14  
 [9] stringi_1.4.3   fs_1.3.1        whisker_0.3-2   rmarkdown_1.13 
[13] tools_3.5.1     stringr_1.4.0   glue_1.3.1      xfun_0.8       
[17] yaml_2.2.0      compiler_3.5.1  htmltools_0.3.6 knitr_1.25