---
title: "Factor analysis, testing and machine learning for bioinformatics"
author: "Bernd Klaus"
date: "`r doc_date()`"
output:
BiocStyle::html_document:
toc: true
highlight: tango
self_contained: true
toc_float: false
code_download: true
df_print: paged
toc_depth: 2
BiocStyle::pdf_document:
toc: true
toc_depth: 2
bibliography: stat_methods_bioinf.bib
---
```{r options, include=FALSE}
library(knitr)
options(digits=3, width=80)
golden_ratio <- (1 + sqrt(5)) / 2
opts_chunk$set(echo=TRUE,tidy=FALSE,include=TRUE,
dev=c('png', 'pdf', 'svg'), fig.height = 5, fig.width = 4 * golden_ratio, comment = ' ', dpi = 300,
cache = TRUE, message = FALSE)
```
**LAST UPDATE AT**
```{r, echo=FALSE, cache=FALSE}
print(date())
```
# Required packages and other preparations
```{r required_packages_and_data, echo = TRUE, cache=FALSE, message=FALSE}
library("readxl")
library("BiocStyle")
library("knitr")
library("MASS")
library("RColorBrewer")
library("stringr")
library("pheatmap")
library("matrixStats")
library("purrr")
library("readr")
library("magrittr")
library("entropy")
library("forcats")
library("DESeq2")
library("broom")
library("tidyverse")
library("limma")
library("ggthemes")
library("corpcor")
library("sva")
library("zinbwave")
library("clusterExperiment")
library("clue")
library("sda")
library("crossval")
library("randomForest")
library("keras")
theme_set(theme_solarized(base_size = 18))
data_dir <- file.path("data")
```
## mTEC single cell-RNA-Seq data import
We first import the mTEC data again.
```{r import_data}
load(file.path(data_dir, "mtec_counts.RData"))
load(file.path(data_dir, "mtec_cell_anno.RData"))
load(file.path(data_dir, "mtec_gene_anno.RData"))
load(file.path(data_dir, "tras.RData"))
```
## Function to compute a PCA
```{r compute_pca}
compute_pca <- function(data_mat, ntop = 500, ...){
pvars <- rowVars(data_mat)
select <- order(pvars, decreasing = TRUE)[seq_len(min(ntop,
length(pvars)))]
PCA <- prcomp(t(data_mat)[, select], center = TRUE, scale. = FALSE)
percentVar <- round(100*PCA$sdev^2/sum(PCA$sdev^2),1)
return(list(pca = data.frame(PC1 = PCA$x[,1], PC2 = PCA$x[,2],
PC3 = PCA$x[,3], PC4 = PCA$x[,4], ...),
perc_var = percentVar,
selected_vars = select))
}
```
# Statistical testing for high--throughput data
In high throughput data we often measure multiple features (e.g. genes) for
which we then perform statistical tests (e.g. for differential expression).
Choosing a p--value significance cutoff \(\alpha\) of e.g. 10%,
classical testing theory tells
us that we will get a false positive result in 10% of the time. This is no
longer true if multiple tests are performed simultaneously. At any \(\alpha\) the probability of making no false rejection goes to zero quite rapidly:
\[
\underbrace{(1-\alpha)\cdot(1-\alpha)\cdot \dotso \cdot (1-\alpha)}_\text{many--times} \rightarrow 0
\]
For an \(\alpha\) of 10% and 50 tests, we get a probability of
0.9^50 = `r 0.9^50` to not make a false rejection. So it is clear that
we need different error measures for the multiple testing situation. Before
we can define them, we need to look at the different error Types.
## Error types and error rates
Suppose you are testing a hypothesis that a fold change $\beta$ equals zero
versus
the alternative that it does not equal zero. Let us assume that there are
$m_0$ non--differentially expressed genes out of $m$ genes and that we declare
$R$ genes as differentially expressed. (i.e. reject the null hypothesis).
These are four possible outcomes:
![](error_rates.png)
* Type I error or false positive --- Say that the fold change
does not equal zero when it does
* Type II error or false negative --- Say that the fold change
equals zero when it doesn't
Just like ordinary significance testing tries to control the false positive
rate, there are two types of rates commonly used in multiple testing procedures:
* Family wise error rate (FWER) -- The probability of at least
one false positive \(\text{Pr}(FP \geq 1)\)
* False discovery rate (FDR) -- The rate of false positives among
all rejected hypothesis \(E\left[\frac{FP}{FP + TP}\right]\)
The FWER is conceptually closely related to classical significance
testing, as it controls the probability of making any false rejection.
However, as we will also see below, using a procedure to control it
is generally too conservative in large scale problems.
The FDR allows for a certain **rate of false positives** and
is the "typical" error rate controlled in large scale
multiple testing problems.
## Statistical testing with RNA--Seq data
Consider the following simulated RNA--Seq data, where we
have simulated two groups with 8 samples in each group and a 1000 genes.
Each group contains 2 batches: males and females. On top of this, there
is genetic information on the subjects which we will use later on in the
discussion of batch effects and unwanted variation.
The data is stored in an `DESeqDataSet`, and we apply a variance stabilization
before we obtain the PCA plot.
```{r sim_rna_seq}
load(file.path(data_dir, "dds_batch.RData"))
dds_batch <- DESeq(dds_batch)
rld_batch <- assay(rlogTransformation(dds_batch, blind=TRUE))
batch_pca <- compute_pca(rld_batch, ntop = 500,
condition = colData(dds_batch)$condition,
sex = colData(dds_batch)$sex,
gen = colData(dds_batch)$gen_back)
sd_ratio <- sqrt(batch_pca$perc_var[2] / batch_pca$perc_var[1])
batch_pca_plot <- ggplot(batch_pca$pca, aes(x = PC1, y = PC2,
color = condition,
shape = sex)) +
geom_point(size = 4) +
ggtitle("PC1 vs PC2, top variable genes") +
labs(x = paste0("PC1, VarExp:", round(batch_pca$perc_var[1],4)),
y = paste0("PC2, VarExp:", round(batch_pca$perc_var[2],4))) +
coord_fixed(ratio = sd_ratio) +
scale_colour_brewer(palette="Dark2")
batch_pca_plot
ggplot(batch_pca$pca, aes(sex, PC2, color = sex)) +
geom_jitter(height = 0, width = 0.1) +
ggtitle("PC2 by sex") +
geom_boxplot(alpha = 0.1) +
scale_color_fivethirtyeight()
```
PC2 captures the sex--related batch effect in our data.
However, PC1 quite clearly separates
the two conditions so we do expect some differentially expressed genes.
### Exercise: sex related batch effect
Use a t--test to compare PC2 between the sex batches.
```{r pc2ttest, results='hide', echo=FALSE}
t.test(PC2 ~ sex, data = (batch_pca$pca))
```
`r Biocpkg("DESeq2") ` performs a test based on generalized linear model (glm).
A generalized linear model is conceptually identical to an ordinary linear model.
However, it allows for non--normally distributed responses. `r Biocpkg("DESeq2") `
uses the negative binomial distribution to model count data.
We can conveniently obtain the results of the test like so:
```{r rna_seq_pval}
load(file.path(data_dir, "dds_batch.RData"))
dds_batch <- DESeq(dds_batch)
res_dds_batch <- results(dds_batch)
res_dds_batch
```
An import diagnostic plot is the histogram of p--values.
```{r rnaSeqPvalHist}
res_dds_batch <- as.data.frame(res_dds_batch)
ggplot(res_dds_batch, aes(x = pvalue)) +
geom_histogram(binwidth = 0.025, boundary = 0 ) +
ggtitle("p-value histogram for simulated RNA-Seq data") +
geom_hline(yintercept = 40, color = "chartreuse3")
```
We see a more or less uniform background, corresponding to genes that
are not differentially expressed and a peak near zero, which represents
the differentially expressed genes. Separating the background from the
peak at zero by eye--balling, we would expect around 40 differently expressed
genes. We do however appreciate the strong dependencies between the values,
seen as little "hills" in the histogram.
We will now explore typical p--value histograms^[See also David Robinson's
[detailed blog post](http://varianceexplained.org/statistics/interpreting-pvalue-histogram/) on that matter.]
## Typical p--value histograms
In order to simulate typical p--value histograms for high--throughput
data, we use the mixture model:
\[
0.75\cdot N(0,1) + 0.25 \cdot N(2,1)
\]
The code below simulates \(m = 200\) \(p\)--values from this model
, i.e. \(m_0 = 150\) here and the null distribution is the
standard normal distribution.
```{r simzscores}
sd.true <- 1
eta0.true <- 0.75
get.random.zscore = function(m = 200)
{
m0 = m*eta0.true
m1 = m-m0
z = c( rnorm(m0, mean = 0, sd = sd.true),
rnorm(m1, mean = 2, sd = 1))
return(z)
}
set.seed(555)
z <- get.random.zscore(200)
```
We compute two sided p--values using the correct null distribution.
```{r pvaluehistogram}
pv <- 2 - 2*pnorm(abs(z), sd = sd.true)
ggplot(tibble(pv), aes(x = pv)) +
geom_histogram(aes(fill = I(tableau_color_pal('tableau10light')(3)[1])),
boundary = 0, binwidth = 0.025) +
xlab("p-values") +
ggtitle("Histogram of p-values, correct null distribution")
```
We see that our \(p\)--values are uniformly distributed under the null hypotheses.
Computing the \(p\)--values assuming a \(N(0,2)\) null distribution
changes the picture.
```{r pvaluehistogramwrongnull}
pv <- 2 - 2*pnorm(abs(z), sd = 2)
ggplot(tibble(pv), aes(x = pv)) +
geom_histogram(aes(fill = I(tableau_color_pal('tableau10light')(3)[2])),
boundary = 0, binwidth = 0.025) +
xlab("p-values") +
ggtitle("Histogram of p-values",
subtitle = "variance of null distribution too high")
```
If the assumed variance of the null distribution is too high, we often see
hill--shaped \(p\)--value histogram. The p--values are to high on average and
we cannot identify the true hits.
If the variance is too low, we get an extreme enrichment in
small p--values, while we potentially loose the uniform background.
### Exercise: p--value histograms
Create a p--value histogram with standard deviation less than 1.
```{r pvaluehistogramwrongnull2, results="hide", fig.show="hide", echo=FALSE}
pv <- 2 - 2*pnorm(abs(z), sd = 0.5)
ggplot(tibble(pv), aes(x = pv)) +
geom_histogram(aes(
fill = I(tableau_color_pal('tableau10light')(3)[3])),
boundary = 0, binwidth = 0.025) +
xlab("p-values") +
ggtitle("Histogram of p-values",
subtitle = "variance of null distribution too low")
```
## Causes of unusual p--value histograms
In practice, it can be very hard to tell what exactly cause an unusual histogram
shape. For example, it can happen if experimental groups show different variability
(e.g. homogeneous controls vs. heterogeneous knockouts).
As tools like `r Biocpkg("DESeq2") ` estimate only one variance parameter per
gene, pooling samples together can lead to variance estimates that are to small
/ to large and hence a wrong null model.
On the other hand, unusual p--values histogram also arise due to unmodelled batch
effects. If batches are known, it can be instructive to compare them to each
other (rather than the experimental groups).
## Controlling the FWER
Traditionally, the FWER, so the probability to make at least one
false rejection is controlled. This directly translates
the usual significance level \(\alpha\) to situations with multiple tests.
The term "family" seems to be a bit unusual, but it simply means a collection
of tests that we consider jointly^[See @Shaffer_1995
for a great review]. A general method to control the FWER is Holm's method,
where the p--value cutoff \(p_k\) is chosen such that
for the ordered p--values \(p_1, \dotsc, p_m\)
with \(p_1 \leq p_2 \leq, \dotsc, \leq p_m\)
\[
p_i \leq \frac{\alpha}{(m-i+1)} \; \text{ for all } \; i \leq k
\]
Where \(\alpha\) is the desired FWER level. This procedure is valid under
arbitrary assumptions and more powerful than the traditionally used Bonferroni
method, which simply multiplies all the p--values
by \(m\).
## Adjusted p--values using Holm's method
Rather than using formal multiples testing procedures directly, in practice
people commonly look at so--called adjusted p--values. Given any test procedure,
the adjusted p--value corresponding to the test of a
single hypothesis \(H_i\) can be defined as the level of
the entire test procedure at
which \(H_i\) would just be rejected,
given the values of all test statistics involved.
So basically, the adjusted p--value tells us about the the \(\alpha\) level
we would achieve if this p--value was chosen as a threshold. For the Holm
method, we can compute adjusted p--values like so:
\[
p_i^\text{Holm} = min\{1, \text{cummax}(m - i + 1) \cdot p_i\}
\]
So we essentially multiply all the p-values by \((m - i + 1)\) and
carry forward the current maximum so that we makes sure that the adjusted
p--values do not decrease --- as required by Holm's rule.
We can conveniently compute Holm--adjusted p--values using the function
`p.adjust`:
```{r holm}
pv <- 2 - 2 * pnorm(abs(z), sd = sd.true)
pv_holm <- p.adjust(pv, method = "holm")
head(pv_holm[pv_holm < 0.1])
z[pv_holm < 0.1]
```
As we can see, the Holm correction is quite conservative, although we have
25 true positives in the data, we only find 3 of them (they have very large
z--scores).
We can also now apply Holm's method to our RNA--Seq data:
```{r holmrnaseq}
res_dds_batch$padj_holm <- p.adjust(res_dds_batch$pvalue,
method = "holm")
table(res_dds_batch$padj_holm < 0.1)
res_dds_batch[res_dds_batch$padj_holm < 0.1,]
```
Where we only identify two genes as differentially expressed.
## Controlling the FDR
As we have seen, control of the FWER can be quite
strict. In a very influential paper, @Benjamini_1995 propose to control the
False Discovery rate (FDR) instead of the FWER. The FDR is the rate of false
discoveries among all rejected null hypothesis. The adjusted p--values are:
\[
p_i^\text{FDR} = min\{1, \text{cummin}\frac{m}{i} \cdot p_i\}
\]
These FDR adjusted p--values can also be computed via `p.adjust`:
```{r bh}
pv <- 2 - 2 * pnorm(abs(z), sd = sd.true)
pv_fdr <- p.adjust(pv, method = "fdr")
table(pv_fdr < 0.1)
z[pv_fdr < 0.1]
```
Using an FDR--adjustment, we actually find `r sum(pv_fdr < 0.1)` significant
z--scores at an FDR of 10%. This means that on average a maximum of
`r round(sum(pv_fdr < 0.1) * 0.1)` in our list are false positives.
`r Biocpkg("DESeq2")` conveniently
computes FDR adjusted p--values for us, we can get on overview by using
the function `summary`:
```{r rna_fdr}
summary(results(dds_batch))
```
Here, we actually only identify a handful of differently expresses genes,
which can be traced back to batch effects and unwanted variation as discussed
next.
# Tackling unwanted variation and batch effects in high--throughput data
High throughput data is often affected by "unwanted variation", i.e.
variation that is not due to the experimental design but technical
and other factors ("batch effects", @Leek_2010).
Classically, batch effects occur because measurements are affected by laboratory
conditions, reagent lots, and personnel differences. This becomes
a major problem when batch effects are confounded with an outcome of interest
and lead to incorrect conclusions. Here we look at some relevant examples
of batch effects and discuss how to detect, interpret, model, and
adjust for batch effects.
Batch effects are the biggest challenge faced by omics research,
especially in the context of precision medicine. The presence
of batch effects in one form or another have been reported among most,
if not all, high-throughput technologies [@Leek_2010].
## Removing known batches via regression
A simple way to remove known
batches is to fit a regression model that includes the batches to the data, and
then subtract the coefficients that belong the batch effects. The function
` removeBatchEffect ` in `limma` implements this strategy.
We specify a batch effect and then a design matrix that incorporates the effects
that we do not want to remove (the experimental condition in this case).
```{r remove_batch_sim}
cleaned_data <- removeBatchEffect(rld_batch,
batch = batch_pca$pca$sex,
design = model.matrix( ~ batch_pca$pca$condition))
cleaned_data_pca <- compute_pca(cleaned_data,
condition = batch_pca$pca$condition,
sex = batch_pca$pca$sex)
sd_ratio <- sqrt(cleaned_data_pca$perc_var[2] / cleaned_data_pca$perc_var[1])
clean_pca_plot <- ggplot(cleaned_data_pca$pca, aes(x = PC1, y = PC2,
color = condition,
shape = sex)) +
geom_point(size = 4) +
ggtitle("PC1 vs PC2, cleaned data, top variable genes") +
labs(x = paste0("PC1, VarExp:", round(cleaned_data_pca$perc_var[1],4)),
y = paste0("PC2, VarExp:", round(cleaned_data_pca$perc_var[2],4))) +
coord_fixed(ratio = sd_ratio) +
scale_colour_brewer(palette="Set2")
clean_pca_plot
ggplot(cleaned_data_pca$pca, aes(sex, PC2, color = sex)) +
geom_jitter(height = 0, width = 0.1) +
ggtitle("PC2 by sex, cleaned data") +
geom_boxplot(alpha = 0.1) +
scale_color_fivethirtyeight()
```
As we can see, the sex effect has been alleviated. The function `ComBat`
from the `r Biocpkg("sva")` implements a more sophisticated method for the removal
of known batches that adjusts the variances in a addition to removal of batch
specific means.^[For additional details see e.g.
[this page](http://genomicsclass.github.io/book/pages/adjusting_with_linear_models.html).]
## Including known batches in a linear model
While the batch effect removal methods often seem to be magic procedures,
they have to be applied carefully. In particular, using the cleaned data
directly can lead to false positive results and exaggerated effects.
The best thing is avoid the direct use of the cleaned data (except for
visualization purposes) and rather include the estimated latent variables
or batch effects into a linear model as the removal might
introduce new biases [@Nygaard_2015, @Jaffe_2015].
We change the design of our `DESeqDataSet` in order to achieve this and
include sex as a "blocking factor" rather than regressing it out:
```{r chgdesign}
design(dds_batch) <- ~ sex + condition
dds_batch_sex <- DESeq(dds_batch)
res_sex <- results(dds_batch_sex)
resultsNames(dds_batch_sex)
```
As we can see, the sex has been included in the linear model. This way,
we partition the mean for every gene into a fold--change and a sex component,
dissecting these two sources of variability.
In fact, it can be shown that running a model like this means that we only
compute fold changes within one sex, rather than using all the data at once.
In experimental design terminology, this is called "blocking" and sex would
be a "blocking factor".
Let's see whether we actually profit from an increased power:
```{r pwrblocking}
summary(res_sex)
```
Indeed, we do: the number of differentially expressed genes detected increases
to `r sum(res_sex$padj < 0.1) ` from `r sum(results(dds_batch)$padj < 0.1)`
previously.
# Factor analysis to tackle unwanted variation
## Factor analysis
Factor analysis^[read about it in [Cosma Shalizi's great book](http://www.stat.cmu.edu/~cshalizi/ADAfaEPoV/)]
is the modelling of data via a small number of latent random variables called
factors. We can use ideas from Factor analysis to tackle batch effects / unwanted
variation. The basic factor analysis takes a \(n \times p\) data matrix (n samples and p
features) and models it via a sum of \(q\) probabilistic factors \(f\) plus an
error term \(E\).
\[
X^{[n \times p]} = \sum_{i = 1}^q f_i^{[n \times 1]} w_i^{[1 \times p]} + E^{[n \times p]} \\
= Fw + E
\]
So just like in PCA, the data is modeled as a weighted sum of new variables.
However, the main and essential difference to PCA is now that the
factors just like the error term are modeled as __random__ rather than deterministic.
(The error terms being independent from the factors and from each other)
Thus, you can think of factors in factor analysis as random versions of
principal components. If we assume that
\[
f_{ij} \sim N(0,1) \text{ for } j = 1, \dotsc, n
\]
and that the factors are independent across samples as well as
variables we get that marginally every variable follows a multivariate
normal distribution with mean zero and correlation \(\varphi_i + w^Tw\).
\[
X_i \sim \mathbf N(0, \varphi_i + w^Tw)
\]
Where \(\varphi_{i}\) are called the "specific variances" and represent the
variances of the error terms; \(w\) is the factor loading matrix.
This equation forms the basis of maximum likelihood estimation in
factor analysis. Factor analysis is often motivated as
"preserving correlations" between the input variables. However,
the term factor analysis is general used for models which include
sums of random variables.
For advanced factor analysis methods in 'omics research see:
@Buettner_2017 and @Argelaguet_2017.
## Factor analysis to tackle batch effects
We can now try factor analysis on our data set: We will use the
variance stabilized data to estimate latent factors. The function
`factanal` will compute those for us. We will try to estimate 4
factors. The function requires a centered and scaled data matrix or a
correlation / covariance matrix as input. Since the function uses maximum
likelihood estimation to obtain the factor loadings, it requires the
inverse of the correlation matrix. However, as we have 1000 genes and
only 16 samples, the usual correlation estimate cannot be inverted and
we need to use a shrinkage estimator of the correlation matrix [@Sch_fer_2005]
as implemented in `r CRANpkg("corpcor")`.
The variables need to be in the
columns, so we need to transpose the `rld` matrix.
Traditionally, the loadings are of primary interest in factor analysis, if
a correlation matrix is given, the function will not even compute the factor
scores. Thus we need to compute them explicitly using a regression method.
```{r runfactor}
factor_ana <- function(X, ntop = 500, ...){
cen_scaled_input <- scale(t(X))
pvars <- colVars(cen_scaled_input)
select <- order(pvars, decreasing = TRUE)[seq_len(min(ntop,
length(pvars)))]
cen_scaled_input <- cen_scaled_input[, select]
cor_matrix <- cor.shrink(cen_scaled_input)
rld_batch_fac <- factanal(covmat = cor_matrix, factors = 4,
n.obs = ncol(cen_scaled_input),
rotation = "none")
loadings <- rld_batch_fac$loadings[, 1:4]
factors <- as_data_frame(cen_scaled_input %*% solve(cor_matrix, loadings)) %>%
add_column(...)
return(factors)
}
```
We can now estimate the factors by maximum likelihood
and create a 2d scatterplot
of them.
```{r runfactanal}
factors_rld_batch <- factor_ana(rld_batch, ntop = 1000,
sex = batch_pca$pca$sex,
condition = batch_pca$pca$condition,
gen = batch_pca$pca$gen)
batch_fac_plot <- ggplot(factors_rld_batch, aes(x = Factor1, y = Factor2,
color = condition,
shape = sex)) +
geom_point(size = 4) +
ggtitle("Factor 1 vs Factor 2, all genes") +
coord_fixed(ratio = sd_ratio) +
scale_colour_tableau(palette = "tableau10")
batch_fac_plot
```
As we can see it is similar to the PCA plot for the data. Although
factor 2 seems to separate the different sexes less than PC2.
This does not have to be the case in general. In fact,
the term `factor analysis` is sometimes employed if PCA--like procedures are
used and some factor analysis estimation algorithms use a PCA--like
algorithm as an initial solution .^[for a detailed description of both methods, I recommend Chap. 16 / 17
of [Shalizi's book](http://www.stat.cmu.edu/~cshalizi/ADAfaEPoV/).]
### Exercise: factor analysis
Try to make sense out of the factors: Check the relationship between Factors 1/2
and condition / sex graphically. Is there a factor which is related to
the genetic background?
```{r facvspca, results="hide", fig.show="hide", echo=FALSE}
ggplot(factors_rld_batch, aes(condition, Factor1, color = condition)) +
geom_jitter(height = 0, width = 0.1) +
ggtitle("Factor 1 by condition") +
geom_boxplot(alpha = 0.1) +
scale_color_fivethirtyeight()
t.test(Factor1 ~ condition, data = factors_rld_batch)
ggplot(factors_rld_batch, aes(sex, Factor2, color = sex)) +
geom_jitter(height = 0, width = 0.1) +
ggtitle("Factor 2 by sex") +
geom_boxplot(alpha = 0.1) +
scale_color_fivethirtyeight()
t.test(Factor2 ~ sex, data = factors_rld_batch)
cor(as.numeric(batch_pca$pca$sex), factors_rld_batch$Factor2)
cor(as.numeric(batch_pca$pca$condition), factors_rld_batch$Factor2)
cor(as.numeric(factors_rld_batch$gen), factors_rld_batch$Factor3)
```
## Including estimated factors in a linear model
We have seen in the plot that factor 1 seems to capture the differences
between groups, while factor 2 captures the sex differences. Factors 3 and 4
seem to be unrelated to the
design. Just like have included sex as a known batch before, we can now
additionally include the computed factors 3, and (or) 4
in the model to see whether this
actually improves power.
```{r factordesign}
colData(dds_batch) <- cbind(colData(dds_batch),
select(factors_rld_batch, 1:4))
design(dds_batch) <- ~ sex + Factor3 + Factor4 + condition
dds_batch_f <- DESeq(dds_batch)
res_f <- results(dds_batch_f)
summary(res_f)
summary(res_sex)
```
The number
of differentially expressed genes detected is now
`r sum(na.exclude(res_f$padj) < 0.1)` compared to `r sum(res_sex$padj < 0.1) `
when only blocking for sex.
## Extending factor analysis to include known covariates
```{r secondfactor}
ggplot(factors_rld_batch, aes(condition, Factor1, color = condition)) +
geom_jitter(height = 0, width = 0.1) +
ggtitle("Factor2 by condition") +
geom_boxplot(alpha = 0.1) +
scale_color_fivethirtyeight()
t.test(Factor2 ~ condition, data = factors_rld_batch)
```
In our factor analysis, we have seen that the first factor
captures the experimental design, and the other factors
seemed to capture unwanted variation we wanted to control for.
Can we somehow formalize this? So can we fit a model like:
data = experimental design + latent factors + noise
that contains both our experimental setup as well as latent factors ?
The answer is "yes", but there is an important difficulty: the latent factors
can be **confounded** with our experimental design.^[See [Wang et. al.](https://arxiv.org/abs/1508.04178) for an
elaboration on that point.] Our simulated RNA--Seq
data contains sex and genetic background as known factors, we
can run a multiple regression analysis of the experimental condition vector
on the known factors to see how much confounding we have:
```{r mult_reg_confounding, warning=FALSE}
confounders <- cbind(as.numeric(colData(dds_batch)$sex),
as.numeric(colData(dds_batch)$gen_back),
as.numeric(colData(dds_batch)$condition))
colnames(confounders) <- c("sex", "gen_back", "condition")
tab_conf <- tidy(lm( confounders[, 1:2] ~ condition,
data = as.data.frame(confounders))) %>%
filter(term != "(Intercept)")
mutate_if(tab_conf, is_numeric, round, digits = 3)
```
As we can see, there is no confounding between sex and condition, but between
the genetic background and the condition. They cannot be easily
disentangled.^[see
also [Gerard and Stephens, 2017](http://dcgerard.github.io/research/2017/06/29/ruv.html)
Popular methods like Surrogate variable analysis, (`r Biocpkg("sva")`)
and RUV (`r Biocpkg("RUVnormalize") ` `r Biocpkg("RUVseq") `, `r Biocpkg("RUVcorr") `)
try to solve this problem by tricks like down weighting genes influenced by the experimental design (so with \(\mathbf{\beta}\) near 0),
robust regression methods (`r CRANpkg("cate") `) or using control genes
to estimate the latent factors.
We will now run sva on our data, to see
whether it can disentangle the latent factors from the experimental
conditions. It requires the definition of a null model, which contains
a priory variables we want to adjust for (like sex) and a full model, which
contains the experimental design + the adjustment variables.
We use the rlog data as an input to sva. First, the total number
of SVs is guessed, then they are
computed.
```{r sva_sim}
mod <- model.matrix(~ sex + condition, data = colData(dds_batch))
mod0 <- model.matrix(~ sex, data = colData(dds_batch))
n.sv <- num.sv(rld_batch, mod, method = "be", B = 100, vfilter = 500)
sva_res <- sva(rld_batch, mod, mod0, n.sv = n.sv, vfilter = 500, B = 20)
ggplot(data_frame(genetic_back = factors_rld_batch$gen,
sv = as.vector(sva_res$sv)),
aes(genetic_back, sv, color = genetic_back)) +
geom_jitter(height = 0, width = 0.1) +
ggtitle("Surrogate variable by genetic background") +
geom_boxplot(alpha = 0.1) +
scale_color_fivethirtyeight()
anova(lm(as.vector(sva_res$sv) ~ factors_rld_batch$gen))
```
Interestingly, the surrogate variable compute seems to capture
the genetic background of our samples. Something that we could not
achieve with PCA or factor analysis alone. Let's look at the power
we have:
```{r svdesign}
colData(dds_batch)$sv <- as.vector(sva_res$sv)
design(dds_batch) <- ~ sv + sex + condition
dds_batch_sva <- DESeq(dds_batch)
res_sva <- results(dds_batch_sva)
summary(res_sva)
```
Unfortunately, although sva is able to capture the genetic background, it
is too confounded with condition leaving us with zero detected genes.
Ultimately, genetic background and experimental conditions are too confounded
with each other, so that we cannot really disentangle the two. It is remarkable
though that sva can actually identify the genetic background from the data.
# Latent factors for sc--RNA Seq: The ZINB-WaVE model
@Brennecke_2015 used the method of @Buettner_2015 to regress out
the influence of the cell cycle from the gene expression data. Briefly,
@Buettner_2015 perform a factor analysis--like algorithm to estimate
a latent factor on gene annotated to cell--cycle. Here, we want to use
the method of @Risso_2018 instead. There is also a more recent
package, `r Biocpkg("scone") `, [@Cole_2018] available from som of the authors which
deals directly with normalization of sc--RNA--Seq data.
They propose a zero--inflated Negative Binomial Model for (sc--) RNA-Seq
data implemented in the package `r Biocpkg("zinbwave")`. In contrast to
many other methods proposed for single cell RNA--Seq data, it uses
the NB distribution, so a distribution
directly tailored to count data.
![](zinba.png)
The model is quite comprehensive.
1. First, it models "additional zeros" as
single cell data RNA--Seq data is commonly thought to contain more zeros
than predicted by the NB distribution. As the additional zeros are believed
to be due to technical factors such the efficiencies of reverse transcription,
these additional zeros are also known as "dropouts".^[On the other hand,
the NB model does not seem to be too bad for sc Data, see e.g. [Valentine Svensson 's] blog
posts on this matter [here](http://www.nxn.se/valent/2017/11/16/droplet-scrna-seq-is-not-zero-inflated) and [here](http://www.nxn.se/valent/2018/1/30/count-depth-variation-makes-poisson-scrna-seq-data-negative-binomial).]
The proportion of zeros is modeled by \(\pi\) while \(mu\) are the counts.
2. The **green component** includes known sample (cell) level covariates such as
the experimental group a sample belongs to. This part is used to reflect
the experimental design and known batches. It includes a column of ones to
account for gene specific baseline expression levels.
3. The **dark blue component** are gene level covariates such as gc--bias or
gene--length corrections.
4. The **red component** contains a factor model which models unknown cell--level
"factors" (random variables) that explain everything that is not captured by
known sample or gene level covariates.
The model also allows for sample--matrix sized offsets, which can be used to
include pre--computed cell specific size factors.
The estimation of the model works by penalized maximum likelihood, where
sets of parameters are optimized at a time: After initialization, the
dispersion is optimized, then the cell specific components and then
the gene specific components.
Finally, it is made sure that the latent factors \(W\) itself as well as
their loading vectors \(\alpha\) are independent of each other,
just as it is assumed in ordinary factor analysis.
## Running zinbwave
We will now run `r Biocpkg("zinbwave")` on the single cell data,
we select only those cells
that were not select based on a surface marker (The other cells
have been used for validation in the original paper). As
`r Biocpkg("zinbwave")` estimates intercept column parameters
as well (by default) we can use the raw counts as input and don't need
to provide our own normalization.
```{r runzinbawave}
no_marker_cells <- filter(mtec_cell_anno, SurfaceMarker == "None")
count_matrix_nomarker <- as.matrix(mtec_counts[, no_marker_cells$cellID])
rownames(count_matrix_nomarker) <- mtec_counts$ensembl_id
#
# zinb <- zinbFit(count_matrix_nomarker,
# K=1, epsilon=1000)
# save(zinb,file = file.path(data_dir, "zinb.RData"))
```
## Obtaining normalized and corrected data
We now obtain the normalized and corrected data. Note that in contrast
to @Brennecke_2015 we do not estimate the latent factor based on genes
annotated to cell cycle but simply let `r Biocpkg("zinbwave")` estimate
one latent factor. We then extract the residuals from the model, i.e.
the green, blue and red parts subtracted from the original data and
store them in a `SingleCellExperiment` object to which we can attach
the cell annotation as `colData`.
```{r zinbanormcorrected}
load(file.path(data_dir, "zinb.RData"))
mtec_norm <- zinbwave(SummarizedExperiment(count_matrix_nomarker),
fitted_model=zinb,
normalizedValues=TRUE,
residuals = TRUE)
# keep only the residuals in the summarized experiment
assay(mtec_norm, 1) <- NULL
assay(mtec_norm, 1) <- NULL
colData(mtec_norm) <- DataFrame(no_marker_cells)
rowData(mtec_norm) <- DataFrame(filter(mtec_gene_anno,
ensembl_id %in% rownames(mtec_norm)))
mtec_norm
```
## Checking the normalization
We check the normalization by creating boxplot for a random set of
25 cells. The boxplots are ordered by median expression. We can
appreciate that the normalization has worked successfully.
```{r checkscnorm}
mtec_norm_tidy <- as.data.frame(assay(mtec_norm)) %>% {
colnames(.) = colData(mtec_norm)$cellID
.[, sample(ncol(mtec_norm), 25)]
} %>%
gather(key = "cell", value = "expression")
medians <- mtec_norm_tidy %>% group_by(cell) %>%
summarize(med = median(expression)) %>%
arrange(med)
mtec_norm_tidy$cell %<>% factor(levels = medians$cell)
pl <- ggplot(mtec_norm_tidy, aes(cell, expression, color = cell)) +
geom_boxplot() +
guides(color = FALSE) +
ggtitle("zinbawave normalized/cleaned expression data [log]") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
pl
#ggsave("norm.pdf", pl, width = 28, height = 14)
```
# Clustering of the normalized and cleaned sc--data
We can now move on to the clustering of the single--cell data and compare
our clusters to the ones from @Brennecke_2015. We will perform the clustering
using the `r Biocpkg("clusterExperiment") ` package, which implements
a comprehensive resampling based clustering strategy called
RSEC (Resampling-based Sequential Ensemble Clustering). It first creates
many clusterings using subsampling and different parameter values for
the clustering algorithms.
It then creates a consensus clustering from those, and finally merges
clusters in this consensus clustering,
which show a low proportion of DE--genes between them.
This avoid erroneous choices of the total number of clusters.
^[A detailed description of the individual steps can be found in the [package vignette](http://bioconductor.org/packages/release/bioc/vignettes/clusterExperiment/inst/doc/clusterExperimentTutorial.html#workflow)]
The package is extremely feature rich, and we will only use as subset of the
available features here to mimic what as done in @Brennecke_2015.
We first import the clustering and subset our data to include only
those genes that were used for clustering in @Brennecke_2015.
We also remove all the genes that were not assigned to a cluster in the
original publication^[this "leftover" cluster has the number 12].
We then add the published clustering to the `rowData` so that we can
compare it to our own clustering.
```{r clusteringprep}
load(file.path(data_dir, "genes_for_clustering.RData"))
load(file.path(data_dir,"nomarkerCellsClustering.RData"))
mtec_norm_sub <- mtec_norm[genes_for_clustering, ]
rowData(mtec_norm_sub)$pub_cls <- cl_class_ids(
nomarkerCellsClustering[["consensus"]])
leftover_genes <- rowData(mtec_norm_sub)$pub_cls == 12
data_for_cl <- assay(mtec_norm_sub[!leftover_genes,])
colnames(data_for_cl) <- colData(mtec_norm_sub)$cellID
```
`r Biocpkg("ClusterExperiment") ` will cluster the cells by default,
while we want to cluster the genes. Thus, we need to feed the transposed
data to the `clusterSingle` command. We run `pam`, a variant of
k--means clustering with a cluster number of 11 and follow a subsampling
strategy: the algorithm is run on subsamples of genes (70% by default)
and then the genes which co--occur often within a cluster
across sub--sampling steps are assigned to a common cluster. So in fact, two
clustering algorithms are used: one for the clustering of the subsamples
and one for the clustering of the co--occurrence matrix
("main clustering).^[See the section
"Internal clustering procedures" in the package vignette for details.]
For both the subsampling as well as the main clustering we use pam with
11 clusters. In order to speed up the computations, we also reduce the
dimensionality of the data via PCA with 10 PCs.
Note that these choices are mainly motivated by the need to save computational
time. In a practical analysis, we would try more tuning parameters and
algorithm variants, like merging of clusters.
```{r runscclustering, eval=FALSE}
cl_mtec <- clusterSingle(t(data_for_cl),
subsample = TRUE,
isCount = FALSE,
clusterLabel = "mtec_sub",
dimReduce = "PCA",
ndims = 10,
mainClusterArgs = list(minSize = 10,
clusterFunction = "pam",
clusterArgs=list(k=11)),
subsampleArgs = list(clusterFunction = "pam",
clusterArgs=list(k=11),
largeDataset = TRUE,
random.seed = 1234,
ncores = 1,
resamp.num = 10))
# save(cl_mtec, file = file.path(data_dir, "cl_mtec.RData"))
```
## Validating the clustering
@Brennecke_2015 report strong co--expression between genes in a cluster,
we now try to see this is as well by inspecting
the correlation matrix ordered by our clustering. We create
a heatmap of the correlation matrix that we save to a pdf document
due to its large size.
```{r validateclustering}
load(file = file.path(data_dir, "cl_mtec.RData"))
row_order <- tibble(genes = rownames(data_for_cl),
clusters = as.numeric(primaryClusterNamed(cl_mtec)),
clusters_org = rowData(mtec_norm_sub)$pub_cls[
rowData(mtec_norm_sub)$pub_cls!=12]) %>%
arrange(clusters) %>%
as.data.frame(.) %>%
{rownames(.) = .$genes
.
}
data_cor <- cor(t( data_for_cl[row_order$genes,]))
br <- seq(-1, 1, length.out=101) ** 3
cols <-
colorRampPalette(brewer.pal(9, "RdBu"), interpolate="spline", space="Lab")(100)
ann_colors = list(
clusters = tableau_color_pal(palette = "tableau20")(11),
clusters_org = tableau_color_pal(palette = "bluered12")(11)
)
pdf("clustering.pdf", width = 14, height = 14,
title = "single cell clustering using zinbawave corrected data")
pheatmap(data_cor,
color = cols,
breaks = br,
cluster_rows = FALSE, cluster_cols = FALSE, legend = TRUE,
legend_labels = NA,
annotation_row = row_order[, "clusters", drop = FALSE],
show_rownames = FALSE,
show_colnames = FALSE,
annotation_colors = ann_colors
)
dev.off()
```
We can appreciate that we do not observe a strong correlation within
the clusters for most of them and we could probably also merge some.
Cluster 10 seems to contain highly correlated genes that are mostly
anti correlated to the rest.
### Exercise: plot original clustering
Create heatmap of the correlation matrix, where the rows / columns are
ordered according to the original clustering. Hint: This is already
part of the data frame `row_order`. You will have to restore the rownames
after the re--ordering of `row_order`
```{r heatorg, results='hide', echo=FALSE}
row_order <- arrange(row_order, clusters_org) %>%
{rownames(.) = .$genes
.
}
pdf("clustering_org.pdf", width = 14, height = 14,
title = "original clustering using zinbawave corrected data")
pheatmap(data_cor[row_order$genes[1:1000], row_order$genes[1:1000]],
color = cols,
breaks = br,
border_color = "grey60", cellwidth = NA, cellheight = NA, scale = "none",
cluster_rows = FALSE, cluster_cols = FALSE, legend = TRUE,
legend_labels = NA,
annotation_row = row_order[, "clusters_org", drop = FALSE],
show_rownames = FALSE,
show_colnames = FALSE,
annotation_colors = ann_colors
)
dev.off()
```
### Exercise: heatmap for cluster 10
Create a heatmap for cluster 10 only, in order to validate that
its genes are indeed highly correlated to each other.
```{r cl10heat, results="hide", echo=FALSE}
idx_10 <- which(row_order$clusters == 10)
pdf("clustering_cl_10.pdf", width = 14, height = 14,
title = "single cell clustering using zinbawave corrected data")
pheatmap(data_cor[idx_10, idx_10],
color = cols,
breaks = br,
border_color = "grey60", cellwidth = NA, cellheight = NA, scale = "none",
cluster_rows = FALSE, cluster_cols = FALSE, legend = TRUE,
legend_labels = NA,
annotation_row = row_order[, "clusters", drop = FALSE],
show_rownames = FALSE,
show_colnames = FALSE,
annotation_colors = ann_colors
)
dev.off()
```
## Dimensionlity reduction + graph building for sc Data
Single cell data is often used to infer (developmental) hierarchies
of single cells. For this, a three step approach has emerged:
1. Dimenionality reduction
2. (optional) Clustering
3. Graph fitting
`r Biocpkg("sincell") ` [@Juli__2015] is a Bioconductor package wrapping a couple
of these techniques, typical examples include `r Biocpkg("monocle") ` and
slingshot [@Street_2017]. Before one uses any of these algorithms, it is always
a good idea to try to obtain robust clusterings via packages like
`r Biocpkg("clusterExperiment") `, as dimensionality reduction step can
be misleading.
In fact, dimensionality reduction methods can result in
trajectory--like patterns for random data. ^[see [W. Huber'examples](https://rpubs.com/WolfgangHuber/143456)]. This is often
related to a certain covariance structure of the data. For an interesting
example of an influential PCA misinterpretation in genetics see @Novembre_2008:
Traditionally, wave-like patterns in PC maps have been interpreted as
migration events. However, as @Novembre_2008 show, these patterns
arise naturally as soon as genetic similarity decays with distance.
For a comprehensive trajectory workflow using the `r Biocpkg("zinbwave")` and `r Biocpkg("clusterExperiment") ` packages, see the paper by @Perraudeau_2017.
# Checking the clustering using machine learning
Another way to "validate" our single--cell clustering is to use machine
learning methods. Specifically, we can treat our cluster numbers as
know class labels and see whether we can predict the cluster assignment
from the gene expression across the single cells.
## Data splitting (cross validation) to avoid optimism
An important ingredient of machine learning is the splitting of the original
data set: training and assessing an algorithm on the same data will give
optimistic estimates of error rates. A common theme employed here is called
**cross--validation**: the data are split into training and tests sets
repeatedly. Typically, 80% are used to train the algorithm and 20% percent
are used to measure the accuracy. This split would be cold 5--fold CV, as
we split the data into 5 parts and then use 4 of them to estimate our model.
## A random forest classifier
We can see from our clustering heatmap that the genes in cluster 10 of our
clustering seem to be correlated to each other while they are anti-correlated to
the rest of the genes. We therefore try to predict
whether a gene is from cluster 10 or not.
For this purpose, we train a **random forest** classifier
which builds on many decision trees: Bootstrap samples (samples with
replacement) are drawn from the data, a decision tree is estimated on
each sample and the results are averaged^[It can be shown that each tree uses 2/3
of the data on average]. This "ensemble"
procedure is also called "bagging" (bootstrap aggregation) and
has been shown to both reduce variance and increase prediction accuracy.
Random forest now adds another ingredient: at each split of the decision
tree: only a random subset of the variables are considered (cells in our case).
This effectively decorrelates the trees: Imagine there is a strong predictor
(cell): it would always be selected, yielding highly similar trees.
However, aggregating correlated trees will decrease the variance
less.^For a detailed introduction to trees and the random forest see
Chapter 8 of the book [introduction to statistical learning](http://www-bcf.usc.edu/~gareth/ISL/index.html).
It has been shown that random forest classifiers deliver a good performance
across a large variety of tasks [@Delgado_14]. Therefore, they are often
a sensible starting point.
We first create a data frame that is ordered according to the input data
and contains the class labels.
```{r prepareDataMl}
genes_clusters <- row_order[rownames(data_for_cl), ] %>%
mutate(labs = factor(ifelse(clusters == 10, "cl10",
"other")))
class_priors <- prop.table(table(genes_clusters$labs))
class_priors
```
As we can see, only `r round(class_priors[1] * 100) ` %
of the data are in cluster 10, thus we have a strong class imbalance.
We run random forest by growing 500 trees and require a minimum of 5
terminal nodes (ensuring that the trees are grown to a sufficient depth).
We use the class proportions as class priors.
As random forest fits each tree to a bootstrap sample of the data,
we can use the "out of bag" samples, i.e. the samples not in the
bootstrap sample for prediction. Thus, the random forest algorithm can
give us out of bag error estimates straight away and also prints them
during the fitting process:
```{r testRF}
rf_fit <- randomForest(x = data_for_cl, y = genes_clusters$labs,
ntree = 500, nodesize = 5,
mtry = floor(sqrt(ncol(data_for_cl))),
classwt = class_priors,
do.trace = 100)
rf_fit$confusion
acc <- 1-sum(rf_fit$confusion[, "class.error"] * class_priors)
acc
```
As we can see, in the out of bag samples, we classify
`r round(rf_fit$confusion[1, 1] /sum(rf_fit$confusion[1, 1:2]) * 100) ` % of
the genes that are in cluster 10 correctly. This is not a very small
error rate, but smaller than for a random classifier discussed next.
## Compare random forest to a random classifier
An random classifier would assign each gene randomly to a class depending
on the class proportions. Thus we would expect an error rate of
`r round(1-class_priors[1] * 100)` % for the prediction of cluster 10.
```{r compareToRandom}
random_cf <- ifelse(rbernoulli(nrow(data_for_cl),
class_priors[1]), "cl10", "other")
random_confusion <- table(random_cf, genes_clusters$labs)
random_confusion <- cbind(random_confusion,
c(random_confusion["other", "cl10"] /
sum(random_confusion[, "cl10"]),
random_confusion["cl10", "other"] /
sum(random_confusion[, "other" ])))
colnames(random_confusion)[3] <- "class.error"
random_confusion
```
Indeed, the RF error rates are lower than expected by chance for
both classes.
## Classification error from cross validation
The out of bag error estimate are often reasonable, but they are only available
for random forest and is more comm. There, we now obtain errors rates from
cross validation.
We use the package `r CRANpkg("crossval")` to perform the cross validation,
it requires a prediction function which takes training and test sets as input
and returns the error rates we are interested in. We now create such a function
for our classifier. We test the function using a random set of 700 genes
as our training data.
```{r predfunForRF}
predfun_rf <- function(train.x, train.y, test.x, test.y, negative){
rf_fit <- randomForest(x = train.x, y = as.factor(train.y),
ntree = 500, nodesize = 5,
mtry = floor(sqrt(ncol(train.x))),
classwt = class_priors,
do.trace = FALSE)
ynew <- predict(rf_fit, test.x)
conf <- table(ynew, test.y)
err_rates <- c(conf["other", "cl10"] /
sum(conf[, "cl10" ]),
conf["cl10", "other"] /
sum(conf[, "other"]))
names(err_rates) <- c("cl10", "other")
return(err_rates)
}
set.seed(123)
train_idx <- sample(nrow(data_for_cl), 700)
test_idx <- setdiff(seq_len(nrow(data_for_cl)), train_idx)
train.x <- data_for_cl[train_idx,]
train.y <- genes_clusters$labs[train_idx]
test.x <- data_for_cl[test_idx, ]
test.y <- genes_clusters$labs[test_idx]
predfun_rf(train.x, train.y,
test.x, test.y)
```
The error rate estimate for cluster 10 is similar to the out of bag
error. Let's see whether we can confirm this via cross validation. We split
the data set repeatedly into K = 5 folds, and use each of theses folds once for
prediction (and the others for training). The number of repeats is B = 10 times,
giving us 50 estimates of the two error rates in total.
In general, choosing a low number of folds will increase the bias, while
a large number of repetitions will decrease the variability of the estimate.
We can then visualize how the prediction errors are distributed within
the repetitions.
```{r doCrossValForRF}
set.seed(789)
rf_out <- crossval(predfun_rf, X = data_for_cl, Y = genes_clusters$labs,
K = 5, B = 10, negative="other", verbose = FALSE)
cv_res <- as.data.frame(rf_out$stat.cv) %>%
rownames_to_column( var = "BF") %>%
extract(col = BF, into = c("rep", "fold"),
regex = "([[:alnum:]]+).([[:alnum:]]+)" ) %>%
mutate_if( is.character, as_factor) %>%
gather(key = "class", value = "pred_error", cl10, other)
cv_plot <- ggplot(cv_res, aes(x = rep, y = pred_error, color = class)) +
geom_jitter(height = 0, width = 0.2) +
ggtitle("CV prediction error by repetitions") +
scale_color_tableau()
cv_plot
```
We can see that the error rate estimates are both large and quite
variable for cluster 10, with the mean being close to the out--of--bag
estimate from random forest.
In general, cluster 10 seems to be hard to predict and the clustering does not
seem to be very strong. On the other hand, the "other" class is easily
predictable, indicating that cluster 10 indeed contains "structure".
# Neural networks
Recent years have seen an increasing interest in (deep) neural networks.
An artificial neural network, initially inspired by neural networks in the brain
consists of layers of interconnected compute units (neurons).
![A Neural Network](Colored_neural_network.svg.png)
In the canonical configuration shown in the figure^[image source: [Wikipedia Commons](https://commons.wikimedia.org/wiki/File:Colored_neural_network.svg)],
the network receives data in
an input layer, which are then transformed in a nonlinear way through (multiple)
hidden layers, before final outputs are computed in the output layer. ^[multiple hidden layers = "deep learning"].
Each neuron computes a weighted sum of its inputs and applies a nonlinear
activation function to calculate its output:
output = activation( input * weights + bias)
The most
popular activation function is the rectified linear unit (ReLU)^[See the
[Wikipedia article](https://en.wikipedia.org/wiki/Rectifier_(neural_networks))]
that thresholds negative signals to 0 and passes through positive signal.
The weights between neurons are free parameters that capture the modelâ€™s
representation of the data and are learned from input/output samples.
Learning minimizes a loss function hat measures the fit of the model output
to the true label of a sample. This minimization is
challenging, since the loss function is high-dimensional and non--convex, similar
to a landscape with many hills and valleys. The loss function is optimized
by changing the weights along its negative gradient. The gradient points
into the direction of steepest ascent, but as minimization of the loss function
is desired, the negative gradient is used.
The gradient is evaluated via the chain rule for derivatives, This, together with
optimization on random batches^[batch = random data sample on which
the current is updated on] of the data is called
"stochastic gradient descent" allows
for efficient training of neural networks. Usually one optimizes the
model during multiple "epochs", where an epoch is one full pass through the
data.^[E.g. If there are 1000 samples and the batch size is 32 an epoch
consists of training on roughly 31 batches]
Alternative architectures to such fully connected feedforward networks have been
developed for specific applications, which differ in the way neurons
are arranged. These include convolutional neural networks, which are widely used
for image analysis and recurrent neural networks for sequential
data, or autoencoders for unsupervised learning.
A concise review of deep learning in biology is given by @Angermueller_2016,
a comprehensive overview of the topic is provided by the book of
@Goodfellow_2016.
^[See also [this](https://keras.rstudio.com/articles/learn.html)
rstudio page with a list of deep learning resources.
@Ching_2018 provides an extensive, "crowd--sourced" overview of deep learning
applications in biology.
## Fitting neural networks with Keras
Creating and fitting neural network architectures used to be technically
challenging. In order to alleviate this tasks, powerful frameworks have
been developed to easily implement the "backend" using the full power
of today's CPUs and GPUs. Here, we use
[TensorFlow](https://www.tensorflow.org/)^[TensorFlow, the TensorFlow logo and any related marks are trademarks of Google Inc.], another popular framework
is [Theano](http://www.deeplearning.net/software/theano/). While these
frameworks make it easier to create and train neural networks^[For a simple
TensorFlow example, see the [paper by P.
Goldsborough](https://arxiv.org/abs/1610.01178)]. However, even though
these frameworks make it easier, they still require quite some expert knowledge
to train neural networks. This is where [Keras](https://keras.io/) comes
in, which builds on top of e.g. TensorFlow in order to provide a high--level
interface that allows for a "natural" definition of neural network architectures.
Keras is written in python, but there is an [R interface as well](https://keras.rstudio.com/).
## A deep feed forward network for the single cell data
Instead of using random forest for prediction, we can also try to train
a deep feed--forward network on the single cell data. We define the network
as follows:
```{r keras_nn, eval=FALSE}
nn <- keras_model_sequential() %>%
layer_dense(units = 32, input_shape = c(203),
name = "input_layer",
kernel_regularizer = regularizer_l1(l = 0.3),
activation = "relu") %>%
layer_dropout(rate = 0.5, name = "input_dropout") %>%
layer_dense(units = 16, name = "hidden_layer_1", activation = "relu") %>%
layer_dense(units = 8, name = "hidden_layer_2", activation = "relu") %>%
layer_dense(bias_initializer = initializer_constant(-5),
units = 1, name = "output_layer", activation = "sigmoid")
```
We have 203 single cells to predict our genes, so the input
layer accepts a vector with 203 entries which the first hidden
layer turns into a an output vector of length 32. We put a penalty
on the weights of the input layer in order to avoid overfitting.
A dropout--layer on the output of the input layer means that
only 50% of units are used at any single training step. This also
helps to avoid overfitting.^[[Overview article on dropout](https://medium.com/@amarbudhiraja/https-medium-com-amarbudhiraja-learning-less-to-learn-better-dropout-in-deep-machine-learning-74334da4bfc5)].
We then use two ordinary hidden layers and then a sigmoidal^[[Wikipedia article](https://en.wikipedia.org/wiki/Sigmoid_function)] output layer
that maps real values to the 0--1 range and that we use to obtain our
classification prediction.
Note that we initialize the bias of the sigmoid to a negative number, this
means that before training, our neural network will favor genes assigned
to cluster 10. This bias will be "unlearned" during the training and we
then stop the training after having obtained a reasonable overall accuracy.
(Here set to 60%)^[This is implemented via a "[callback](https://keras.rstudio.com/articles/training_callbacks.html)"]
This way, we hope to obtain a better per--class error for cluster 10 than
the 60% we get from the random forest. We again assess this via
cross--validation.^[Note that we need to turn the text labels into
zeros and ones as this is the output of our network]
```{r nn_cv, eval=TRUE}
predfun_nn <- function(train.x, train.y, test.x, test.y, negative){
# create a custom callback that will stop model training if the
# overall accuracy is greater than some threshold
# this is checked per batch
acc_stop <- R6::R6Class("acc_stop",
inherit = KerasCallback,
public = list(
accs = NULL,
cl10errors = NULL,
on_batch_end = function(batch, logs = list()) {
self$accs <- c(self$accs, logs[["binary_accuracy"]])
self$cl10errors <- c(self$cl10errors, logs[["cl10_errors"]])
if(logs[["binary_accuracy"]] > 0.6){
self$model$stop_training = TRUE
}
}
))
call_acc_stop <- acc_stop$new()
nn <- keras_model_sequential() %>%
layer_dense(units = 32, input_shape = c(203),
name = "input_layer",
kernel_regularizer = regularizer_l1(l = 0.3),
activation = "relu") %>%
layer_dropout(rate = 0.5, name = "input_dropout") %>%
layer_dense(units = 16, name = "hidden_layer_1", activation = "relu") %>%
layer_dense(units = 8, name = "hidden_layer_2", activation = "relu") %>%
layer_dense(bias_initializer = initializer_constant(-5),
units = 1, name = "output_layer", activation = "sigmoid")
nn %>%
compile(optimizer = 'adam',
loss = loss_binary_crossentropy,
metrics = 'binary_accuracy')
nn %>%
fit(train.x,
train.y,
epochs=50, batch_size=64, verbose = 0,
callbacks = list(call_acc_stop))
ynew <- predict_classes(nn, test.x)
rm(nn)
k_clear_session()
conf <- table(ynew, test.y)
if(nrow(conf) != 2){
conf <- rbind(conf, c(0,0))
}
if(ncol(conf) != 2){
conf <- cbind(conf, c(0,0))
}
colnames(conf) <- rownames(conf) <- c("cl10", "other")
err_rates <- c(conf["other", "cl10"] /
sum(conf[, "cl10"]),
conf["cl10", "other"] /
sum(conf[, "other"]))
names(err_rates) <- c("cl10", "other")
return(err_rates)
}
set.seed(789)
labs_nn <- as.numeric(genes_clusters$labs) - 1
nn_out <- crossval(predfun_nn, X = data_for_cl, Y = labs_nn,
K = 5, B = 10, negative="other", verbose = FALSE)
cv_res_nn <- as.data.frame(nn_out$stat.cv) %>%
rownames_to_column( var = "BF") %>%
extract(col = BF, into = c("rep", "fold"),
regex = "([[:alnum:]]+).([[:alnum:]]+)" ) %>%
mutate_if( is.character, as_factor) %>%
gather(key = "class", value = "pred_error", cl10, other)
cv_plot_nn <- ggplot(cv_res_nn, aes(x = rep, y = pred_error, color = class)) +
geom_jitter(height = 0, width = 0.2) +
ggtitle("CV prediction error by repetitions") +
scale_colour_gdocs()
cv_plot_nn
```
Our "bias strategy" does lower the prediction error for cluster 10 a bit,
however, it strongly increases the error for the "other" class.
Neural networks offer a high degree of flexibility overall and we can easily
tune them towards certain objectives. However, in our data set, it
is intrinsically hard to predict cluster 10 so that lowering the error
rate for this class, will strongly increase the rate for the other class.
In practice, data over- or undersampling is used to overcome classed
unbalancedness. Note that simply repeating data is not useful, as this usually
decreases the variance of the features in the minority class and can lead
to too optimistic results. Sampling with replacement or techniques like
SMOTE (Synthetic Minority Oversampling TEchnique, @Chawla_2005).
# Session Info
```{r session_info, cache = FALSE}
sessionInfo()
```
```{r unloaAll, echo=FALSE, message=FALSE, eval = FALSE}
pkgs <- loaded_packages() %>%
filter(package != "devtools") %>%
{.$path}
walk(pkgs, unload)
```
# References