evaluate-classification-naive-bayes


Evaluate classification accuracy

This notebook demonstrates how to evaluate classification accuracy of "novel taxa". Due to the unique nature of this analysis, the metrics that we use to evaluate classification accuracy of "novel taxa" are different from those used for mock and simulated communities.

The key measure here is rate of match vs. overclassification, hence P/R/F are not useful metrics. Instead, we define and measure the following as percentages:

  • Match vs. overclassification rate
    • Match: assignment == L - 1 (e.g., a novel species is assigned the correct genus)
    • overclassification: assignment == L (e.g., correct genus but assigns to a near neighbor)
    • misclassification: incorrect assignment at L - 1 (e.g., wrong genus-level assignment)

Where L = taxonomic level being tested

Functions


In [1]:
from tax_credit.framework_functions import novel_taxa_classification_evaluation
from tax_credit.eval_framework import parameter_comparisons
from tax_credit.plotting_functions import (pointplot_from_data_frame,
                                           heatmap_from_data_frame,
                                           per_level_kruskal_wallis,
                                           rank_optimized_method_performance_by_dataset)

from os.path import expandvars, join, exists
from glob import glob
from IPython.display import display, Markdown
import pandas as pd

Evaluate classification results

First, enter in filepaths and directory paths where your data are stored, and the destination


In [2]:
project_dir = "../.."
analysis_name = "novel-taxa-simulations"
precomputed_results_dir = join(project_dir, "data", "precomputed-results", analysis_name)
expected_results_dir = join(project_dir, "data", analysis_name)
summary_fp = join(precomputed_results_dir, 'evaluate_classification_summary.csv')

results_dirs = glob(join(precomputed_results_dir, '*', '*', '*', '*'))

This cell performs the classification evaluation and should not be modified.


In [3]:
force = False
if force or not exists(summary_fp):
    accuracy_results = novel_taxa_classification_evaluation(results_dirs, expected_results_dir, summary_fp)
else:
    accuracy_results = pd.DataFrame.from_csv(summary_fp)

Plot classification accuracy

Finally, we plot our results. Line plots show the mean +/- 95% confidence interval for each classification result at each taxonomic level (1 = phylum, 6 = species) in each dataset tested. Do not modify the cell below, except to adjust the color_pallette used for plotting. This palette can be a dictionary of colors for each group, as shown below, or a seaborn color palette.

Precision = Proportion of classifications that were correct. For novel taxa, this means a match at the last common ancestor (LCA) (level-1). True Positives / (True Positives + False Positives)

Recall = Proportion of reads that were correctly classified. Equals the number of exact matches to the LCA. True Positives / (True Positives + False Negatives)

F-measure = Harmonic mean of Precision and Recall

overclassification_ratio = proportion of taxa that were assigned to correct lineage but to a deeper taxonomic level than expected, rather than to LCA. E.g., assignment to another species in the clade

underclassification_ratio = proportion of assignments to correct lineage but to a lower level than expected.

misclassification_ratio = proportion of assignments to an incorrect lineage.


In [4]:
color_pallette={
    'rdp': 'seagreen', 'sortmerna': 'gray', 'vsearch': 'brown',
    'uclust': 'blue', 'blast': 'black', 'blast+': 'purple', 'q2-nb': 'pink',
    'naive-bayes': 'orange'
}

y_vars = ["Precision", "Recall", "F-measure",
          "overclassification_ratio", 
          "underclassification_ratio", "misclassification_ratio"]

Plot per-level classification accuracy

For novel-taxa analysis, a separate classification is performed at each taxonomic level using different test (unique taxa at level L) and training sets (ref - test taxonomies). Hence, results at each level L represent independent tests, unlike for mock and simulated communities where each level represents the accuracy of each species-level classification trimmed to level L. For novel taxa, results at level L indicate the accuracy with with method M assigns the correct lineage to a "novel" taxon, which is unrepresented in the reference at level L, e.g., level 6 indicates the performance with which each classifier assigns the correct genus to each species.


In [5]:
pointplot_from_data_frame(accuracy_results, "level", y_vars, 
                          group_by="Dataset", color_by="Method",
                          color_pallette=color_pallette)


Naive-Bayes k-mer length picker


In [6]:
from pandas import DataFrame, concat, to_numeric

In [7]:
nb_results = accuracy_results[accuracy_results['Method'] == 'naive-bayes']
nb_results = nb_results.reset_index(drop=True)
columns = ['Alpha', 'kmer', 'Confidence']
def decode_params(p):
    p = p.split(':')
    p[-2] = int(eval(p[-2])[0])
    return p
params = DataFrame((decode_params(s) for s in nb_results['Parameters']), columns=columns)
keepers = ['Dataset', 'level', 'Method']
metrics = y_vars
raw_param_results = concat([nb_results[keepers + metrics], params], axis=1)
raw_param_results = raw_param_results.apply(to_numeric, errors='ignore')
param_results = raw_param_results.groupby(keepers + columns, as_index=False).mean()
param_results.level = param_results.level.astype(int)
param_results.kmer = param_results.kmer.astype(int)
len(param_results)


Out[7]:
1296

In [8]:
level_pallete = {n:'blue' for n in range(1,6)}
level_pallete[6] = 'orange'
pointplot_from_data_frame(param_results, "kmer", y_vars, 
                          group_by="Dataset", color_by="level",
                          color_pallette=level_pallete)


Per-level classification accuracy statistic

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


In [20]:
result = per_level_kruskal_wallis(accuracy_results, y_vars, group_by='Method', 
                                  dataset_col='Dataset', alpha=0.05, 
                                  pval_correction='fdr_bh')
result


Out[20]:
Dataset Variable 1 2 3 4 5 6
0 B1-REF Precision 8.241441e-46 8.822214e-25 9.259168e-15 5.969736e-15 2.506888e-05 1.357682e-07
1 B1-REF Recall 8.241441e-46 2.041312e-22 3.837822e-13 4.403113e-14 4.326535e-08 5.267536e-15
2 B1-REF F-measure 8.241441e-46 2.735165e-23 8.656979e-14 1.637687e-14 2.646422e-07 1.806480e-13
3 B1-REF overclassification_ratio 4.326535e-08 4.884334e-05 4.853095e-10 3.076997e-16 3.194018e-08 3.006092e-07
4 B1-REF underclassification_ratio 1.585365e-54 1.037442e-10 1.160336e-09 7.272181e-10 9.051610e-13 1.039314e-09
5 B1-REF misclassification_ratio 3.622453e-16 2.393009e-07 6.867733e-08 1.028754e-11 3.678470e-14 7.280989e-06
6 F1-REF Precision 8.044413e-40 9.955331e-20 7.218849e-10 1.265124e-09 6.464274e-08 4.514306e-10
7 F1-REF Recall 8.044413e-40 2.209889e-17 4.254808e-13 4.404391e-09 2.568263e-10 2.024411e-14
8 F1-REF F-measure 8.044413e-40 1.954399e-18 4.671006e-12 1.758706e-08 1.939320e-09 1.801307e-14
9 F1-REF overclassification_ratio 4.223413e-28 4.559576e-38 3.665587e-15 1.193339e-20 9.964955e-17 3.613000e-15
10 F1-REF underclassification_ratio 1.128081e-78 6.277483e-36 2.751610e-25 8.681525e-24 1.637687e-14 2.027388e-19
11 F1-REF misclassification_ratio 2.499674e-122 2.120068e-35 7.012532e-34 6.147361e-31 7.718474e-23 2.935985e-16

Heatmaps of method accuracy by parameter

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


In [21]:
heatmap_from_data_frame(accuracy_results, metric="Precision", rows=["Method", "Parameters"], cols=["Dataset", "level"])



In [22]:
heatmap_from_data_frame(accuracy_results, metric="Recall", rows=["Method", "Parameters"], cols=["Dataset", "level"])