Evaluate mock community classification accuracy

The purpose of this notebook is to evaluate taxonomic classification accuracy of mock communities using different classification methods.

Prepare the environment

First we'll import various functions that we'll need for generating the report.


In [1]:
from shutil import copytree

%matplotlib inline
from os.path import join, exists, expandvars
import pandas as pd
from IPython.display import display, Markdown
import seaborn.xkcd_rgb as colors
from tax_credit.plotting_functions import (pointplot_from_data_frame,
                                           boxplot_from_data_frame,
                                           heatmap_from_data_frame,
                                           per_level_kruskal_wallis,
                                           beta_diversity_pcoa,
                                           average_distance_boxplots,
                                           rank_optimized_method_performance_by_dataset)
from tax_credit.eval_framework import (evaluate_results,
                                       method_by_dataset_a1,
                                       parameter_comparisons,
                                       merge_expected_and_observed_tables,
                                       filter_df)

Configure local environment-specific values

This is the only cell that you will need to edit to generate basic reports locally. After editing this cell, you can run all cells in this notebook to generate your analysis report. This will take a few minutes to run, as results are computed at multiple taxonomic levels.

Values in this cell will not need to be changed, with the exception of project_dir, to generate the default results contained within tax-credit. To analyze results separately from the tax-credit precomputed results, other variables in this cell will need to be set.


In [2]:
## project_dir should be the directory where you've downloaded (or cloned) the 
## tax-credit repository. 
project_dir = join('..', '..')

## expected_results_dir contains expected composition data in the structure
## expected_results_dir/<dataset name>/<reference name>/expected/
expected_results_dir = join(project_dir, "data/precomputed-results/", "mock-community")

## mock_results_fp designates the files to which summary results are written.
## If this file exists, it can be read in to generate results plots, instead
## of computing new scores.
mock_results_fp = join(expected_results_dir, 'mock_results.tsv')

## results_dirs should contain the directory or directories where
## results can be found. By default, this is the same location as expected 
## results included with the project. If other results should be included, 
## absolute paths to those directories should be added to this list.
results_dirs = [expected_results_dir]

## directory containing mock community data, e.g., feature table without taxonomy
mock_dir = join(project_dir, "data", "mock-community")

## Minimum number of times an OTU must be observed for it to be included in analyses. Edit this
## to analyze the effect of the minimum count on taxonomic results.
min_count = 1

## Define the range of taxonomic levels over which to compute accuracy scores.
## The default given below will compute order (level 2) through species (level 6)
taxonomy_level_range = range(2,7)

In [3]:
dataset_ids = ['mock-1', 'mock-2', 'mock-3', 'mock-4', 'mock-5', 'mock-7', 'mock-8', 'mock-9',
               'mock-10', 'mock-12', 'mock-16', 'mock-18', 'mock-19', 'mock-20', 'mock-21', 
               'mock-22', 'mock-23', 'mock-24', 'mock-26-ITS1', 'mock-26-ITS9']
reference_ids = ['gg_13_8_otus_full', 'gg_13_8_otus_amplicon', 'gg_13_8_otus_read',
                 'unite_20.11.2016_clean_full', 'unite_20.11.2016_clean_amplicon',
                 'unite_20.11.2016_clean_read']

Find mock community pre-computed tables, expected tables, and "query" tables

Next we'll use the paths defined above to find all of the tables that will be compared. These include the pre-computed result tables (i.e., the ones that the new methods will be compared to), the expected result tables (i.e., the tables containing the known composition of the mock microbial communities), and the query result tables (i.e., the tables generated with the new method(s) that we want to compare to the pre-computed result tables).

Note: if you have added additional methods to add, set append=True. If you are attempting to recompute pre-computed results, set force=True.

This cell will take a few minutes to run if new results are being added, so hold onto your hat. If you are attempting to re-compute everything, it may take an hour or so, so go take a nap.


In [4]:
for mock in dataset_ids:
    md = join(expected_results_dir, mock)
    if exists(join(md, 'gg_13_8_otus', 'expected')):
        src = join(md, 'gg_13_8_otus', 'expected')
        dsts = [join(md, 'gg_13_8_otus_full', 'expected'),
                join(md, 'gg_13_8_otus_amplicon', 'expected')]
        for dst in dsts:
            if not exists(dst):
                copytree(src, dst)
    elif exists(join(md, 'unite_20.11.2016_clean_fullITS', 'expected')):
        src = join(md, 'unite_20.11.2016_clean_fullITS', 'expected')
        dsts = [join(md, 'unite_20.11.2016_clean_full', 'expected'),
                join(md, 'unite_20.11.2016_clean_amplicon', 'expected')]
        for dst in dsts:
            if not exists(dst):
                copytree(src, dst)
    else:
        raise ValueError('no expected sequences for ' + mock)

In [5]:
mock_results = evaluate_results(results_dirs, 
                                expected_results_dir, 
                                mock_results_fp, 
                                mock_dir,
                                dataset_ids=dataset_ids,
                                reference_ids=reference_ids,
                                taxonomy_level_range=range(2,7), 
                                min_count=min_count,
                                taxa_to_keep=None, 
                                md_key='taxonomy', 
                                subsample=False,
                                per_seq_precision=True,
                                exclude=['other'],
                                method_ids=['naive-bayes', 'naive-bayes-bespoke'],
                                append=False,
                                force=False)


../../data/precomputed-results/mock-community/mock_results.tsv already exists.
Reading in pre-computed evaluation results.
To overwrite, set force=True
Results have been filtered to only include datasets or reference databases or methods or parameters that are explicitly set by results params. To disable this function and load all results, set dataset_ids and reference_ids and method_ids and parameter_ids to None.

In [6]:
mock_results['Reference'].unique()


Out[6]:
array(['gg_13_8_otus_amplicon', 'gg_13_8_otus_full',
       'unite_20.11.2016_clean_amplicon', 'unite_20.11.2016_clean_full'], dtype=object)

Restrict analyses to a set of datasets or references: e.g., exclude taxonomy assignments made for purpose of reference database comparisons. This can be performed as shown below — alternatively, specific reference databases, datasets, methods, or parameters can be chosen by setting dataset_ids, reference_ids, method_ids, and parameter_ids in the evaluate_results command above.


In [7]:
mock_results = filter_df(mock_results, column_name='Reference',
                         values=['gg_13_8_otus_amplicon', 'gg_13_8_otus_full',
                                 'unite_20.11.2016_clean_full'], exclude=False)

Compute and summarize precision, recall, and F-measure for mock communities

In this evaluation, we compute and summarize precision, recall, and F-measure of each result (pre-computed and query) based on the known composition of the mock communities. We then summarize the results in two ways: first with boxplots, and second with a table of the top methods based on their F-measures. Higher scores = better accuracy

As a first step, we will evaluate average method performance at each taxonomic level for each method within each reference dataset type.

Note that, as parameter configurations can cause results to vary widely, average results are not a good representation of the "best" results. See here for results using optimized parameters for each method.

First we will define our color palette and the variables we want to plot. Via seaborn, we can apply the xkcd crowdsourced color names. If that still doesn't match your hue, use hex codes.


In [8]:
color_pallette={
    'naive-bayes': 'blue', 'naive-bayes-bespoke': 'orange'
}

y_vars = ["Precision", "Recall", "F-measure", "Taxon Accuracy Rate", "Taxon Detection Rate"]

In [9]:
pointplot_from_data_frame(mock_results, "Level", y_vars, 
                          group_by="Reference", color_by="Method",
                          color_pallette=color_pallette)


Kruskal-Wallis between-method accuracy comparisons

Kruskal-Wallis FDR-corrected p-values comparing classification methods at each level of taxonomic assignment


In [10]:
result = per_level_kruskal_wallis(mock_results, y_vars, group_by='Method', 
                                  dataset_col='Reference', level_name='Level',
                                  levelrange=range(2,7), alpha=0.05, 
                                  pval_correction='fdr_bh')
result


Out[10]:
Reference Variable 2 3 4 5 6
0 gg_13_8_otus_amplicon Precision 1.960670e-03 1.019334e-05 6.739288e-05 5.031753e-06 1.615352e-32
1 gg_13_8_otus_amplicon Recall 8.086396e-05 1.286304e-28 7.241147e-42 4.458385e-66 3.492438e-35
2 gg_13_8_otus_amplicon F-measure 4.042680e-03 4.623718e-36 3.097654e-37 1.766276e-51 8.671458e-39
3 gg_13_8_otus_amplicon Taxon Accuracy Rate 3.616809e-05 2.455151e-11 5.498455e-12 4.232587e-42 1.390476e-85
4 gg_13_8_otus_amplicon Taxon Detection Rate 4.403981e-02 4.440301e-02 6.512317e-08 2.687402e-36 2.417777e-86
5 gg_13_8_otus_full Precision 5.806095e-01 5.819929e-02 2.460518e-01 1.314067e-03 4.119984e-10
6 gg_13_8_otus_full Recall 6.507456e-29 1.120827e-38 3.117530e-51 4.311157e-70 3.664723e-37
7 gg_13_8_otus_full F-measure 4.736172e-13 5.366400e-35 9.959653e-40 6.215868e-58 1.896108e-36
8 gg_13_8_otus_full Taxon Accuracy Rate 2.844237e-11 3.152589e-26 2.486038e-27 4.498244e-66 1.972071e-91
9 gg_13_8_otus_full Taxon Detection Rate 5.464334e-02 4.403981e-02 8.942429e-15 5.535279e-41 8.171599e-83
10 unite_20.11.2016_clean_full Precision 1.926170e-01 5.798501e-04 1.803638e-04 2.734875e-06 3.845802e-11
11 unite_20.11.2016_clean_full Recall 1.134852e-11 8.110902e-12 1.085118e-11 5.551952e-12 5.531389e-43
12 unite_20.11.2016_clean_full F-measure 2.299182e-08 6.341756e-09 4.873023e-10 8.483605e-10 1.190454e-29
13 unite_20.11.2016_clean_full Taxon Accuracy Rate 8.734955e-10 2.543535e-10 1.932514e-10 4.503136e-13 9.051197e-26
14 unite_20.11.2016_clean_full Taxon Detection Rate 2.309001e-10 4.226215e-11 2.185211e-13 1.543458e-16 3.599178e-27

Heatmaps of per-level accuracy

Heatmaps show the performance of individual method/parameter combinations at each taxonomic level, in each reference database (i.e., for bacterial and fungal mock communities individually).


In [11]:
heatmap_from_data_frame(mock_results, metric="Precision", rows=["Method", "Parameters"], cols=["Reference", "Level"])



In [12]:
heatmap_from_data_frame(mock_results, metric="Recall", rows=["Method", "Parameters"], cols=["Reference", "Level"])



In [13]:
heatmap_from_data_frame(mock_results, metric="F-measure", rows=["Method", "Parameters"], cols=["Reference", "Level"])



In [14]:
heatmap_from_data_frame(mock_results, metric="Taxon Accuracy Rate", rows=["Method", "Parameters"], cols=["Reference", "Level"])



In [15]:
heatmap_from_data_frame(mock_results, metric="Taxon Detection Rate", rows=["Method", "Parameters"], cols=["Reference", "Level"])


Now we will focus on results at species level (for genus level, change to level 5)


In [16]:
mock_results_6 = mock_results[mock_results['Level'] == 4]

In [17]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="Precision", color_pallette=color_pallette)



In [18]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="Recall", color_pallette=color_pallette)



In [19]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="F-measure", color_pallette=color_pallette)



In [20]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="Taxon Accuracy Rate", color_pallette=color_pallette)



In [21]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="Taxon Detection Rate", color_pallette=color_pallette)


In the following heatmaps, we assess accuracy rates in each dataset X method configuration combination. This allows us to assess how evenly configurations affect performance, whether specific mock communities outperform of underperform relative to others, and generally assess how increasing/decreasing specific parameters affects accuracy.


In [22]:
heatmap_from_data_frame(mock_results_6, "Precision")



In [23]:
heatmap_from_data_frame(mock_results_6, "Recall")



In [24]:
heatmap_from_data_frame(mock_results_6, "F-measure")



In [25]:
heatmap_from_data_frame(mock_results_6, "Taxon Accuracy Rate")



In [26]:
heatmap_from_data_frame(mock_results_6, "Taxon Detection Rate")



In [27]:
mock_results_6 = mock_results[mock_results['Level'] == 6]

In [28]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="Precision", color_pallette=color_pallette)



In [29]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="Recall", color_pallette=color_pallette)



In [30]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="F-measure", color_pallette=color_pallette)



In [31]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="Taxon Accuracy Rate", color_pallette=color_pallette)



In [32]:
boxplot_from_data_frame(mock_results_6, group_by="Method", metric="Taxon Detection Rate", color_pallette=color_pallette)


In the following heatmaps, we assess accuracy rates in each dataset X method configuration combination. This allows us to assess how evenly configurations affect performance, whether specific mock communities outperform of underperform relative to others, and generally assess how increasing/decreasing specific parameters affects accuracy.


In [33]:
heatmap_from_data_frame(mock_results_6, "Precision")