Algorithm Search⌘K

Algorithmresearch

GENIE3

Also called tree-based network inference, gene network inference with ensemble of trees.

For each gene, fit a random forest that predicts it from the other genes, and rank the links from regulator to target by the importance of the regulator.

Time
O(m T K n^2 log n) worst
Space
Θ(m^2 + m n) extra
Where
K = the number of inputs tried at each node; T = the number of trees per target; m = the number of genes; n = the number of samples
Properties
randomizednot exactofflinerecursive
Origin
Vân Anh Huynh Thu, Alexandre Irrthum, Louis Wehenkel, Pierre Geurts, 2010

GENIE3 turns gene regulatory network inference into mm regression problems, one for each of the mm genes. For a target gene jj, it fits a random forest of regression trees that predicts the expression of jj from the expression of the candidate regulators, and it scores each regulator ii by how much the splits on ii reduce the squared error of the trees. The score wijw_{ij} is the weight of the directed link from ii to jj, and the output is the list of all links sorted by weight. Trees catch nonlinear effects and interactions of regulators, which a correlation misses. GENIE3 is a heuristic: it has no guarantee that the top links are the true ones, and its results on a data set are measurements. The code of this page is a small version of the method: it keeps the Random Forest trees, grown to full depth, and the variance reduction importance, and it leaves out the Extra-Trees variant, the default of 1000 trees per target and the parallel runs over the targets.

In plain words

Pick one gene and try to predict its level in each sample from the levels of all the other genes. A regression tree does this by asking yes or no questions such as "is gene A above some value?", and each question splits the samples into two groups whose levels are more alike. A question that makes the groups much more alike is a useful question, and the gene it asks about gets credit for it.

Grow many such trees, each on a random sample of the data and with a random choice of genes to ask about at each step, and add up the credit of each gene. Genes with a lot of credit are good predictors of the chosen gene, so they are candidate regulators. Do this for every gene in turn and sort all the links by their credit.

The problem

Input. An expression matrix with mm genes and nn samples, xgsx_{g s}; optionally a list of candidate regulators, for example the known transcription factors; the number TT of trees per target and the number KK of inputs tried at each node.

Output. A list of directed links (i,j)(i, j), i≠ji \neq j, ii a candidate regulator, with weights wij≥0w_{ij} \ge 0, sorted by decreasing weight. A user cuts the list at some rank to get a network. GENIE3 gives no sign and no threshold.

For a set SS of samples (with repeats) and the target values ysy_s, write SS(S)=∑s∈S(ys−yˉS)2=∣S∣⋅Var(S)\mathrm{SS}(S) = \sum_{s \in S} (y_s - \bar y_S)^2 = |S| \cdot \mathrm{Var}(S) for the sum of squares about the mean of SS. A split of SS on input ii at threshold tt sends the samples with xis≤tx_{i s} \le t to the left part SLS_L and the others to SRS_R. Its reduction is

Δ=SS(S)−SS(SL)−SS(SR)=σL2∣SL∣+σR2∣SR∣−σ2∣S∣,\Delta = \mathrm{SS}(S) - \mathrm{SS}(S_L) - \mathrm{SS}(S_R) = \frac{\sigma_L^2}{|S_L|} + \frac{\sigma_R^2}{|S_R|} - \frac{\sigma^2}{|S|},

where σ\sigma, σL\sigma_L and σR\sigma_R are the sums of yy over SS, SLS_L and SRS_R. This is the quantity #S⋅Var(S)−#St⋅Var(St)−#Sf⋅Var(Sf)\#S \cdot \mathrm{Var}(S) - \#S_t \cdot \mathrm{Var}(S_t) - \#S_f \cdot \mathrm{Var}(S_f) of the paper. The importance of input ii in one tree is the sum of Δ\Delta over all nodes of the tree that split on ii.

The algorithm

  1. GENIE3(X, T, K)
  2. 1for each target gene j do
  3. 2y ← row j of X divided by its standard deviation; inputs ← the candidate regulators other than j
  4. 3for t ← 1 to T do
  5. 4S ← n samples drawn with replacement from the n samples
  6. 5grow a regression tree on S; at each node, draw K inputs at random and take the split with the largest reduction Δ
  7. 6for each node that splits on input i do w[i, j] ← w[i, j] + Δ / T
  8. 7sort all pairs (i, j) by w[i, j], largest first
  9. 8return the sorted list

Line L2 scales each target to unit variance. Without it, a target with a large variance would give large reductions and would fill the top of the list. Line L4 is the bootstrap sample of a random forest. Line L5 grows the tree to full depth: a node is a leaf when its target values are all equal or no input takes two values on it. For one input, the best threshold comes from one sort of the node's samples by that input and one pass with running sums, which gives Δ\Delta for every cut between two distinct values. Line L6 adds the reductions to the weights as the tree grows. The paper uses T=1000T = 1000 and K=pK = \sqrt{p} or K=pK = p for pp candidate inputs, and also an Extra-Trees variant in which line L5 draws the cut point at random.

Example

Take three genes A, B and C and four samples, with C as the target. Let A take the values 1, 2, 3, 4, let B take the values 4, 1, 4, 1, and let C take the values 0, 2, 1, 3. So C is 2 when B is low, plus 1 when A is high. The mean of C is 1.5 and SS=2.25+0.25+0.25+2.25=5\mathrm{SS} = 2.25 + 0.25 + 0.25 + 2.25 = 5, so Var=1.25\mathrm{Var} = 1.25; scaling divides by 1.25\sqrt{1.25}, which multiplies every sum of squares by 0.80.8. The steps below use the raw values and scale at the end. Use all samples once (no bootstrap) and K=2K = 2.

At the root, the cuts on A give, from left to right, reductions 0+36/3−9=30 + 36/3 - 9 = 3, 4/2+16/2−9=14/2 + 16/2 - 9 = 1 and 9/3+9/1−9=39/3 + 9/1 - 9 = 3. The only cut on B separates the samples with B = 1 (C values 2 and 3) from those with B = 4 (C values 0 and 1), with reduction 25/2+1/2−9=425/2 + 1/2 - 9 = 4. So the root splits on B with Δ=4\Delta = 4. Each child has two samples with equal B and different A, and the split on A gives Δ=0.5\Delta = 0.5 in each. All four leaves are pure. The raw importances are 4 for B and 1 for A, and after scaling wBC=3.2w_{BC} = 3.2 and wAC=0.8w_{AC} = 0.8. They add up to 4=n4 = n, as the theorem below says for a fully grown tree.

On simulated data. The test of the implementation uses 6 genes and 100 samples (seed 1). Genes 0, 1 and 2 are independent normal regulators. Gene 3 is tanh⁡(2x0)\tanh(2 x_0) plus noise, gene 4 is x2x_2 when x1>0x_1 > 0 and 0 otherwise, plus noise, and gene 5 is x22x_2^2 plus noise, each with noise of standard deviation 0.3. With genes 0, 1 and 2 as candidate regulators there are 15 candidate links, 4 of them true. With T=30T = 30 trees and K=2K = 2, the top 4 links contain 3 true links, and the area under the ROC curve is 38/44=0.86438/44 = 0.864. The link from 2 to 5 is second. Ranking by the absolute Pearson correlation gives an area of 34/44=0.77334/44 = 0.773 and puts the link from 2 to 5 sixth, because x22x_2^2 is not correlated with x2x_2. The link from 1 to 4 is tenth: gene 1 acts only as a switch for gene 2, and it gets less weight than the links between the free regulators. This is one measurement, not a guarantee.

Correctness

GENIE3 is a heuristic, so the claims here are about what the code computes, not about recovery of the true network.

Theorem. (a) For each node and each tried input, line L5 finds the threshold with the largest reduction Δ\Delta. (b) In each tree, the importances of all inputs add up to SS(S)−∑leaves ℓSS(ℓ)\mathrm{SS}(S) - \sum_{\text{leaves } \ell} \mathrm{SS}(\ell). If every leaf is pure, they add up to SS(S)\mathrm{SS}(S); with no bootstrap this is nn, since yy has unit variance, and with a bootstrap sample its expected value is n−1n - 1. (c) The weights do not change when an input gene is replaced by a strictly increasing function of itself, for the same random draws.

Part (a) holds because a threshold split depends only on the position of the cut in the sorted order of the input, and the sweep visits every cut between two distinct values. Part (b) holds because each split replaces SS\mathrm{SS} of a node by the sum of SS\mathrm{SS} of its children, so the reductions telescope from the root to the leaves. Part (c) holds because a strictly increasing map keeps the sorted order and the ties of the input, so every node sees the same set of cuts with the same reductions. The proof file gives the details.

Part (b) has a practical consequence. With fully grown trees and continuous data, every target gives a total weight of about nn to its inputs, whether it has a regulator or not. A target with no regulator spreads that weight over its inputs, and some of these false links can rank above weak true links, as in the example above.

Proof: What GENIE3 computes, the sum of its importances and its invariancefull

Setup. Fix a target yy with 1n∑s(ys−yˉ)2=1\frac1n \sum_s (y_s - \bar y)^2 = 1 (line L2) and the input rows xix_i. A node holds a multiset SS of samples. For a multiset UU, let σ(U)=∑s∈Uys\sigma(U) = \sum_{s \in U} y_s and SS(U)=∑s∈U(ys−yˉU)2\mathrm{SS}(U) = \sum_{s \in U} (y_s - \bar y_U)^2, with SS(∅)=0\mathrm{SS}(\emptyset) = 0. A split of SS on input ii at threshold tt gives SL={s∈S:xis≤t}S_L = \{s \in S : x_{i s} \le t\} and SR=S∖SLS_R = S \setminus S_L, both non-empty, and its reduction is Δ=SS(S)−SS(SL)−SS(SR)\Delta = \mathrm{SS}(S) - \mathrm{SS}(S_L) - \mathrm{SS}(S_R). GENIE3 makes no claim about recovery of the true network; the statements below are about the computed weights.

Lemma 1. Δ=σ(SL)2/∣SL∣+σ(SR)2/∣SR∣−σ(S)2/∣S∣\Delta = \sigma(S_L)^2 / |S_L| + \sigma(S_R)^2 / |S_R| - \sigma(S)^2 / |S|, and Δ≥0\Delta \ge 0.

Proof. For any multiset UU, SS(U)=∑s∈Uys2−σ(U)2/∣U∣\mathrm{SS}(U) = \sum_{s \in U} y_s^2 - \sigma(U)^2 / |U|. The sums of ys2y_s^2 over SLS_L and SRS_R add up to the sum over SS, so they cancel in Δ\Delta, which leaves the formula. Δ≥0\Delta \ge 0 because SS(S)\mathrm{SS}(S) is the least value of ∑s∈S(ys−c)2\sum_{s \in S} (y_s - c)^2 over one constant cc, while SS(SL)+SS(SR)\mathrm{SS}(S_L) + \mathrm{SS}(S_R) is the least value over one constant on each part. □\square

Lemma 2 (the split search). For a node SS and a list of inputs, the split search returns a split of the largest reduction among all threshold splits on these inputs, or reports that none exists when no input takes two values on SS.

Proof. Fix an input ii. Sort SS by xix_i, as s1,…,s∣S∣s_1, \ldots, s_{|S|}. Every threshold tt that gives two non-empty parts sends to the left a prefix s1,…,sqs_1, \ldots, s_q, where xisq≤t<xisq+1x_{i s_q} \le t < x_{i s_{q+1}}, so xisq<xisq+1x_{i s_q} < x_{i s_{q+1}}. Conversely, each such qq is reached by the midpoint threshold. So the threshold splits on ii are exactly the prefixes that end between two distinct values. The search visits every qq from 1 to ∣S∣−1|S| - 1, keeps the running sum σ({s1,…,sq})\sigma(\{s_1, \ldots, s_q\}), skips the qq with equal values, and evaluates Δ\Delta by Lemma 1. It keeps the largest value over all inputs. If no input takes two values, no qq is evaluated and the search reports none. □\square

Lemma 3 (telescoping). For a tree grown on SS with leaves ℓ1,…,ℓr\ell_1, \ldots, \ell_r, the reductions of all its splits add up to SS(S)−∑q=1rSS(ℓq)\mathrm{SS}(S) - \sum_{q=1}^{r} \mathrm{SS}(\ell_q).

Proof. By induction on the number of splits. A tree with no split is one leaf SS, and both sides are 0. Otherwise the root splits SS into SLS_L and SRS_R with reduction SS(S)−SS(SL)−SS(SR)\mathrm{SS}(S) - \mathrm{SS}(S_L) - \mathrm{SS}(S_R), and the two subtrees have fewer splits. By induction their reductions add up to SS(SL)\mathrm{SS}(S_L) minus the sum over the leaves of the left subtree, and to SS(SR)\mathrm{SS}(S_R) minus the sum over the leaves of the right subtree. Adding the three terms gives the claim. □\square

Theorem. (a) Line L5 takes, at each node, the split of largest reduction over the KK drawn inputs. (b) The importances of all inputs in one tree add up to SS(S)−∑qSS(ℓq)\mathrm{SS}(S) - \sum_q \mathrm{SS}(\ell_q). If every leaf is pure, they add up to SS(S)\mathrm{SS}(S), which is nn when SS is all samples once and has expected value n−1n - 1 when SS is a bootstrap sample of size nn. (c) If an input row xix_i is replaced by g(xi)g(x_i) for a strictly increasing gg, then with the same random draws the weights do not change.

Proof. (a) is Lemma 2. (b) The importance of an input is the sum of Δ\Delta over the splits on it, so the sum over all inputs is the sum over all splits, and Lemma 3 gives the first claim. A pure leaf has SS=0\mathrm{SS} = 0. With all samples once, SS(S)=n⋅1=n\mathrm{SS}(S) = n \cdot 1 = n. For a bootstrap sample, the nn draws Y1,…,YnY_1, \ldots, Y_n are independent and uniform on the values ysy_s, with mean yˉ\bar y and variance 1. Then E[∑k(Yk−Yˉ)2]=(n−1)⋅1\mathrm{E}[\sum_k (Y_k - \bar Y)^2] = (n - 1) \cdot 1 by the usual identity ∑k(Yk−Yˉ)2=∑k(Yk−yˉ)2−n(Yˉ−yˉ)2\sum_k (Y_k - \bar Y)^2 = \sum_k (Y_k - \bar y)^2 - n (\bar Y - \bar y)^2, whose expected value is n−n⋅1n=n−1n - n \cdot \tfrac1n = n - 1.

(c) A strictly increasing gg keeps the order of the values of xix_i and keeps equal values equal and distinct values distinct. So at every node, the set of splits on input ii, given as sets SLS_L, is the same before and after the change, and so are their reductions by Lemma 1, which depend on yy only. The draws of line L4 and of the inputs at each node do not depend on the values of the inputs, but only on the number of samples and on which nodes are split; by induction on the depth, the two runs split the same nodes into the same parts and draw the same numbers. So every tree has the same splits, up to the value of the thresholds, and the same reductions, and the weights are equal. □\square

Remark. Part (b) shows that, for full trees and continuous data, the weights into each target add up to about nn whatever the true network is. So a weight is meaningful only relative to the other weights of the same target and of the other targets, and the ranking of line L7 is a heuristic.

Complexity

The model is the real RAM. At a node with ss samples, each of the KK tried inputs costs a sort, O(slog⁡s)O(s \log s), and a pass, O(s)O(s). The nodes of one depth of a tree hold at most nn samples in all, so one depth costs O(Knlog⁡n)O(K n \log n). A tree of depth dd costs O(dKnlog⁡n)O(d K n \log n), and d≤nd \le n. So one target costs O(TKn2log⁡n)O(T K n^2 \log n) in the worst case and all targets O(mTKn2log⁡n)O(m T K n^2 \log n). For balanced trees, d=O(log⁡n)d = O(\log n) and the cost is O(mTKnlog⁡2n)O(m T K n \log^2 n); presorting each input once per tree removes one log⁡n\log n factor. Huynh-Thu et al. describe the cost as nearly linear in the number of samples, and at most quadratic in the number of genes when KK grows with the number of genes. The weights take Θ(m2)\Theta(m^2) space, the data Θ(mn)\Theta(m n), and one tree O(n)O(n). The targets are independent, so they can run in parallel.

Properties

  • Randomized. The bootstrap samples and the inputs tried at each node are random, so the weights change with the seed. A larger TT makes them more stable.
  • Directed, unsigned. A link from ii to jj means that ii helps to predict jj. It does not say whether ii activates or represses jj, and for two genes that both are candidates the two directions get separate weights that are often similar.
  • Invariant to increasing transforms of the inputs. Splits depend only on the order of each input, so a log transform of the inputs changes nothing. The targets are scaled, but not transformed, so a transform of a target does change its weights.
  • Nonlinear. Trees fit thresholds and interactions, so a regulator that acts only above some level, or only together with another regulator, can still get weight.

Variants and improvements

  • Extra-Trees. Geurts, Ernst and Wehenkel (2006) draw one random cut point for each tried input instead of the best one. Huynh-Thu et al. report results for both tree methods.
  • Known regulators. Restrict the inputs to the transcription factors. This removes the links between targets and most of the links into genes that have no regulator in the list.
  • GRNBoost2. Moerman et al. (2019) replace the forest by gradient boosting with early stopping, which is much faster on large single cell data sets, and keep the same scheme of one regression per gene.
  • Time series. dynGENIE3 (Huynh-Thu and Geurts 2018) predicts the rate of change of a target from the levels of the regulators, with a model of decay, so that the time order of the samples is used.
  • Other regression scores. Any method that gives an importance per input fits the same scheme, for example a sparse linear regression per target. DREAM5 (Marbach et al. 2012) found that the best regression methods, GENIE3 among them, were among the strongest single methods, and that an average of the ranks of many methods was more robust than any single one.

When to use it

Use GENIE3 for steady state expression data from many conditions, when you want a ranked list of candidate regulators for each target and the effects may be nonlinear. It needs no assumption on the form of the effects and no discretization of the data. Prefer ARACNE when you want an undirected, sparse network with a clear rule for removing indirect links, a sparse linear model when the number of samples is small, and a dynamic Bayesian network or dynGENIE3 when the data is a time series.

Pitfalls

  • Correlated regulators share weight. If two regulators carry the same information, the trees use one or the other at random, and each gets about half the weight. Neither may reach the top of the list.
  • Every target gives out the same total. With full trees the weights into each target add up to about nn, so the links into an unregulated gene look as strong as real links. Restrict the inputs to known regulators where possible.
  • The top of the list is not a network. The output is a ranking. A cut at some rank is a choice of the user, and the paper scores the whole ranking by the areas under the ROC and the precision and recall curves.
  • Direction is weak evidence. For two genes that are both candidates, the weights of the two directions are similar, and a large difference is not proof of the direction of control.
  • Random seed. With few trees, the order of links with close weights changes from seed to seed. Report the seed and use enough trees.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

genie3.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/genie3/. The authors are listed in prov/NVTX2V.jsonl.
"""GENIE3: rank regulatory links by the importance of each gene in tree ensembles.

The expression data is a list of m genes, and each gene is a list of n samples
(floats). Genes are numbered 0 .. m-1. For each target gene j, the code scales
row j to unit variance, grows T regression trees that predict it from the
candidate regulators, and sums the importance of each regulator over the trees.

This is a small version of the method of Huynh-Thu et al. (2010). It keeps the
Random Forest variant (bootstrap samples and K random inputs at each node),
fully grown trees and the variance reduction importance. It leaves out the
Extra-Trees variant, the default of 1000 trees, parallel runs over targets,
and any filtering of the final list.

Random draws. All draws come from one random.Random passed in by the caller,
in this order: targets in index order; for each target, trees in order; for
each tree, first n calls rng.randrange(n) for the bootstrap sample (only when
bootstrap is on), then the nodes in depth-first order, left child first, with
one call rng.sample(inputs, K) at each node with at least min_split samples
and a positive sum of squares (only when K is less than the number of inputs).
"""

from __future__ import annotations

import math
from typing import Dict, List, Optional, Sequence, Tuple

Link = Tuple[int, int, float]


def scale_to_unit_variance(y: Sequence[float]) -> List[float]:
    """Divide y by its population standard deviation (a constant y is left as zeros)."""
    n = len(y)
    mean = sum(y) / n
    var = sum((v - mean) ** 2 for v in y) / n
    if var <= 0.0:
        return [0.0] * n
    sd = math.sqrt(var)
    return [v / sd for v in y]


def sum_of_squares(y: Sequence[float], idx: Sequence[int]) -> float:
    """Sum of squared deviations from the mean of y over the samples idx: #S * Var(S)."""
    if not idx:
        return 0.0
    mean = sum(y[s] for s in idx) / len(idx)
    return sum((y[s] - mean) ** 2 for s in idx)


def best_split(x: Sequence[Sequence[float]], y: Sequence[float], idx: Sequence[int], features: Sequence[int]):
    """Best threshold split of the samples idx over the given input rows.

    Returns (reduction, feature, threshold), or None if no feature takes two
    values on idx. The reduction is #S Var(S) - #L Var(L) - #R Var(R), which
    equals sL^2/nL + sR^2/nR - s^2/n for the sums s of y. Ties keep the first
    feature in the given order and the leftmost threshold.
    """
    n = len(idx)
    total = sum(y[s] for s in idx)
    base = total * total / n
    best = None
    for f in features:
        row = x[f]
        order = sorted(idx, key=lambda s: row[s])
        left = 0.0
        for pos in range(n - 1):
            left += y[order[pos]]
            a, b = row[order[pos]], row[order[pos + 1]]
            if a == b:
                continue
            nl = pos + 1
            right = total - left
            red = left * left / nl + right * right / (n - nl) - base
            if best is None or red > best[0]:
                best = (red, f, (a + b) / 2.0)
    return best


class Node:
    __slots__ = ("feature", "threshold", "left", "right", "value")

    def __init__(self, value: float):
        self.feature = -1
        self.threshold = 0.0
        self.left: Optional[Node] = None
        self.right: Optional[Node] = None
        self.value = value


def grow_tree(rng, x, y, idx, inputs, k, importance: Dict[int, float], min_split: int = 2) -> Node:
    """Grow a regression tree on the samples idx (with repeats) and add to importance.

    A node is split when it has at least min_split samples, its sum of squares
    is positive and some candidate input takes two values on it.
    """
    node = Node(sum(y[s] for s in idx) / len(idx))
    if len(idx) < min_split or sum_of_squares(y, idx) <= 1e-12:
        return node
    feats = list(inputs) if k >= len(inputs) else rng.sample(list(inputs), k)
    split = best_split(x, y, idx, feats)  # @line L5
    if split is None:
        return node
    red, f, thr = split
    importance[f] = importance.get(f, 0.0) + red  # @line L6
    node.feature, node.threshold = f, thr
    node.left = grow_tree(rng, x, y, [s for s in idx if x[f][s] <= thr], inputs, k, importance, min_split)
    node.right = grow_tree(rng, x, y, [s for s in idx if x[f][s] > thr], inputs, k, importance, min_split)
    return node


def predict(node: Node, x: Sequence[Sequence[float]], s: int) -> float:
    """Prediction of the tree for sample s of the input rows x."""
    while node.left is not None:
        node = node.left if x[node.feature][s] <= node.threshold else node.right
    return node.value


def target_importances(rng, x, y, inputs, n_trees: int, k: int, bootstrap: bool = True) -> Dict[int, float]:
    """Mean over n_trees trees of the importance of each input for the target y."""
    n = len(y)
    total: Dict[int, float] = {f: 0.0 for f in inputs}
    for _ in range(n_trees):  # @line L3
        if bootstrap:
            idx = [rng.randrange(n) for _ in range(n)]  # @line L4
        else:
            idx = list(range(n))
        imp: Dict[int, float] = {}
        grow_tree(rng, x, y, idx, inputs, k, imp)
        for f, v in imp.items():
            total[f] += v
    return {f: v / n_trees for f, v in total.items()}


def genie3(
    rng,
    data: Sequence[Sequence[float]],
    n_trees: int = 50,
    k: Optional[int] = None,
    regulators: Optional[Sequence[int]] = None,
    bootstrap: bool = True,
) -> List[Link]:
    """Ranked list of links (regulator, target, weight), largest weight first.

    k is the number of inputs tried at each node; None means round(sqrt(p)),
    at least 1, for p candidate inputs. regulators restricts the candidate
    regulators (all genes by default). Ties in weight are ordered by
    (regulator, target).
    """
    m = len(data)
    regs = list(range(m)) if regulators is None else sorted(set(regulators))
    weights: List[Link] = []
    for j in range(m):  # @line L1
        y = scale_to_unit_variance(data[j])  # @line L2
        inputs = [i for i in regs if i != j]
        if not inputs:
            continue
        kk = max(1, round(math.sqrt(len(inputs)))) if k is None else k
        imp = target_importances(rng, data, y, inputs, n_trees, kk, bootstrap)
        for i in inputs:
            weights.append((i, j, imp[i]))
    weights.sort(key=lambda t: (-t[2], t[0], t[1]))  # @line L7
    return weights  # @line L8


def auroc(scores: Sequence[float], labels: Sequence[bool]) -> float:
    """Area under the ROC curve: the chance that a random positive outscores a random negative (ties count 1/2)."""
    pos = [s for s, l in zip(scores, labels) if l]
    neg = [s for s, l in zip(scores, labels) if not l]
    wins = 0.0
    for a in pos:
        for b in neg:
            wins += 1.0 if a > b else 0.5 if a == b else 0.0
    return wins / (len(pos) * len(neg))
test_genie3.py 185 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/genie3/. The authors are listed in prov/NVTX2V.jsonl.

import math
import random

from genie3 import (
    auroc,
    best_split,
    genie3,
    grow_tree,
    predict,
    scale_to_unit_variance,
    sum_of_squares,
    target_importances,
)


def brute_force_best_reduction(x, y, idx, features):
    """Try every feature and every observed value as a threshold, with direct sums of squares."""
    best = None
    whole = sum_of_squares(y, idx)
    for f in features:
        for t in sorted(set(x[f][s] for s in idx)):
            left = [s for s in idx if x[f][s] <= t]
            right = [s for s in idx if x[f][s] > t]
            if not left or not right:
                continue
            red = whole - sum_of_squares(y, left) - sum_of_squares(y, right)
            if best is None or red > best:
                best = red
    return best


def simulate(rng, n):
    """Genes 0, 1, 2 are free regulators; 3, 4, 5 are targets.

    Draw order per sample: x0, x1, x2 with rng.gauss, then the noise of genes 3, 4 and 5.
    """
    data = [[0.0] * n for _ in range(6)]
    for s in range(n):
        x0, x1, x2 = rng.gauss(0, 1), rng.gauss(0, 1), rng.gauss(0, 1)
        data[0][s], data[1][s], data[2][s] = x0, x1, x2
        data[3][s] = math.tanh(2 * x0) + 0.3 * rng.gauss(0, 1)
        data[4][s] = (x2 if x1 > 0 else 0.0) + 0.3 * rng.gauss(0, 1)
        data[5][s] = x2 * x2 + 0.3 * rng.gauss(0, 1)
    return data


TRUTH = {(0, 3), (1, 4), (2, 4), (2, 5)}


def pearson(a, b):
    n = len(a)
    ma, mb = sum(a) / n, sum(b) / n
    sab = sum((u - ma) * (v - mb) for u, v in zip(a, b))
    sa = math.sqrt(sum((u - ma) ** 2 for u in a))
    sb = math.sqrt(sum((v - mb) ** 2 for v in b))
    return sab / (sa * sb)


def test_scale_to_unit_variance():
    y = scale_to_unit_variance([1.0, 2.0, 4.0, 7.0])
    mean = sum(y) / 4
    assert abs(sum((v - mean) ** 2 for v in y) / 4 - 1.0) < 1e-12
    assert scale_to_unit_variance([3.0, 3.0]) == [0.0, 0.0]


def test_split_matches_brute_force():
    rng = random.Random(1)
    for _ in range(300):
        p, n = rng.randint(1, 4), rng.randint(2, 12)
        x = [[rng.choice([rng.random(), float(rng.randint(0, 3))]) for _ in range(n)] for _ in range(p)]
        y = [rng.gauss(0, 1) for _ in range(n)]
        idx = [rng.randrange(n) for _ in range(n)]  # repeats, as in a bootstrap sample
        feats = list(range(p))
        got = best_split(x, y, idx, feats)
        want = brute_force_best_reduction(x, y, idx, feats)
        if want is None:
            assert got is None
        else:
            assert abs(got[0] - want) < 1e-9


def test_full_tree_importances_sum_to_the_total_sum_of_squares():
    rng = random.Random(2)
    for _ in range(30):
        p, n = rng.randint(1, 4), rng.randint(5, 40)
        x = [[rng.random() for _ in range(n)] for _ in range(p)]
        y = scale_to_unit_variance([rng.gauss(0, 1) for _ in range(n)])
        imp = {}
        tree = grow_tree(rng, x, y, list(range(n)), list(range(p)), p, imp)
        # distinct inputs, so every leaf is pure and the tree fits the data
        assert abs(sum(imp.values()) - n) < 1e-8
        for s in range(n):
            assert abs(predict(tree, x, s) - y[s]) < 1e-9


def test_bootstrap_importances_sum_to_the_bootstrap_sum_of_squares():
    # with K equal to the number of inputs, the bootstrap draws are the only draws
    rng = random.Random(3)
    n, p, trees = 30, 3, 5
    x = [[rng.random() for _ in range(n)] for _ in range(p)]
    y = scale_to_unit_variance([rng.gauss(0, 1) for _ in range(n)])
    imp = target_importances(random.Random(9), x, y, list(range(p)), trees, p, bootstrap=True)
    replay = random.Random(9)
    want = 0.0
    for _ in range(trees):
        idx = [replay.randrange(n) for _ in range(n)]
        want += sum_of_squares(y, idx)
    assert abs(sum(imp.values()) - want / trees) < 1e-8


def test_step_target_gives_all_importance_to_its_regulator():
    rng = random.Random(4)
    n = 50
    x = [[rng.random() for _ in range(n)] for _ in range(3)]
    y = scale_to_unit_variance([1.0 if v > 0.5 else 0.0 for v in x[1]])
    imp = target_importances(rng, x, y, [0, 1, 2], 1, 3, bootstrap=False)
    assert abs(imp[1] - n) < 1e-9
    assert imp[0] == 0.0 and imp[2] == 0.0


def test_worked_example_of_the_page():
    # genes A, B, C = 0, 1, 2; C is 2 when B is low, plus 1 when A is high
    data = [[1.0, 2.0, 3.0, 4.0], [4.0, 1.0, 4.0, 1.0], [0.0, 2.0, 1.0, 3.0]]
    y = scale_to_unit_variance(data[2])
    rng = random.Random(0)
    imp = {}
    tree = grow_tree(rng, data, y, [0, 1, 2, 3], [0, 1], 2, imp)
    assert tree.feature == 1
    assert abs(imp[1] - 3.2) < 1e-12 and abs(imp[0] - 0.8) < 1e-12
    raw = best_split(data, data[2], [0, 1, 2, 3], [0])
    assert abs(raw[0] - 3.0) < 1e-12
    links = genie3(random.Random(0), data, n_trees=1, k=2, regulators=[0, 1], bootstrap=False)
    assert [(i, j) for i, j, _ in links if j == 2] == [(1, 2), (0, 2)]


def test_increasing_transform_of_the_inputs_changes_nothing():
    rng = random.Random(5)
    n, p = 40, 4
    x = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(p)]
    y = scale_to_unit_variance([x[0][s] * x[1][s] + rng.gauss(0, 0.2) for s in range(n)])
    x2 = [[math.exp(v) for v in row] if f % 2 == 0 else [v ** 3 for v in row] for f, row in enumerate(x)]
    a = target_importances(random.Random(11), x, y, list(range(p)), 10, 2)
    b = target_importances(random.Random(11), x2, y, list(range(p)), 10, 2)
    for f in range(p):
        assert abs(a[f] - b[f]) < 1e-9


def test_same_seed_same_ranking():
    data = simulate(random.Random(6), 40)
    a = genie3(random.Random(12), data, n_trees=5)
    b = genie3(random.Random(12), data, n_trees=5)
    assert a == b
    assert len(a) == 6 * 5
    assert all(a[q][2] >= a[q + 1][2] for q in range(len(a) - 1))


def test_auroc_small_case():
    assert auroc([3, 2, 1], [True, False, False]) == 1.0
    assert auroc([1, 2, 3], [True, False, False]) == 0.0
    assert auroc([1, 1], [True, False]) == 0.5


def test_recovery_on_simulated_data_is_measured():
    # a measurement for one seed, not a guarantee: 6 genes, 100 samples, 30 trees
    rng = random.Random(1)
    data = simulate(rng, 100)
    links = genie3(rng, data, n_trees=30, regulators=[0, 1, 2])
    pairs = [(i, j) for i, j, _ in links]
    assert len(pairs) == 15
    labels = [q in TRUTH for q in pairs]
    corr = {q: abs(pearson(data[q[0]], data[q[1]])) for q in pairs}
    by_corr = sorted(pairs, key=lambda q: (-corr[q], q))
    # the numbers quoted on the page
    assert sum(labels[:4]) == 3
    assert round(auroc([w for _, _, w in links], labels) * 44) == 38
    assert round(auroc([corr[q] for q in pairs], labels) * 44) == 34
    assert pairs.index((2, 5)) + 1 == 2 and by_corr.index((2, 5)) + 1 == 6
    assert pairs.index((1, 4)) + 1 == 10
    # each target's weights sum to about n, whether or not it has a regulator
    for j in range(6):
        total = sum(w for _, t, w in links if t == j)
        assert 90 < total < 110

History

Breiman introduced random forests and their variable importance in 2001, and Geurts, Ernst and Wehenkel introduced Extra-Trees in 2006. Huynh-Thu, Irrthum, Wehenkel and Geurts applied tree ensembles to network inference as GENIE3 in 2010, and GENIE3 was the best method in the DREAM4 In Silico Size 100 Multifactorial challenge. It was also one of the top methods in DREAM5. Huynh-Thu and Geurts extended it to time series as dynGENIE3 in 2018, and Moerman et al. published the faster GRNBoost2 in 2019.

References

  1. Vân Anh Huynh-Thu, Alexandre Irrthum, Louis Wehenkel and Pierre Geurts, Inferring regulatory networks from expression data using tree-based methods, PLoS ONE 5(9), e12776, 2010, the method section (one regression problem per gene, unit variance outputs, Random Forests and Extra-Trees, the variance reduction importance), the complexity discussion and the DREAM4 results
  2. Leo Breiman, Random forests, Machine Learning 45(1), 5-32, 2001, random forests for regression and the importance of the input variables
  3. Pierre Geurts, Damien Ernst and Louis Wehenkel, Extremely randomized trees, Machine Learning 63(1), 3-42, 2006, the Extra-Trees algorithm, with random cut points
  4. Daniel Marbach et al., Wisdom of crowds for robust gene network inference, Nature Methods 9(8), 2012, the DREAM5 comparison of network inference methods, in which GENIE3 is among the best regression methods
  5. Thomas Moerman, Sara Aibar Santos, Carmen Bravo González-Blas, Jaak Simm, Yves Moreau, Jan Aerts and Stein Aerts, GRNBoost2 and Arboreto, efficient and scalable inference of gene regulatory networks, Bioinformatics 35(12), 2159-2161, 2019, GRNBoost2, the gradient boosting variant of the GENIE3 scheme
  6. Vân Anh Huynh-Thu and Pierre Geurts, dynGENIE3, dynamical GENIE3 for the inference of gene networks from time series expression data, Scientific Reports 8, 3384, 2018, the extension of GENIE3 to time series data

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example