-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathcross_validate.py
343 lines (304 loc) · 14.1 KB
/
cross_validate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# ----------------------------------------------------------------------------
# Copyright (c) 2019-2023, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------------------------------------------------
import pandas as pd
import qiime2 as q2
import timeit
from warnings import filterwarnings
from sklearn.model_selection import StratifiedKFold
from q2_types.feature_data import DNAFASTAFormat, DNAIterator
from .evaluate import _taxonomic_depth, _process_labels
def evaluate_fit_classifier(ctx,
sequences,
taxonomy,
reads_per_batch='auto',
n_jobs=1,
confidence=0.7):
'''
taxonomy: FeatureData[Taxonomy] artifact of taxonomy labels
sequences: FeatureData[Sequence] artifact of sequences
k: number of kfold cv splits to perform.
'''
# Validate inputs
start = timeit.default_timer()
taxa, seq_ids = _validate_cross_validate_inputs(taxonomy, sequences)
taxa = taxa.loc[seq_ids]
taxonomy = q2.Artifact.import_data('FeatureData[Taxonomy]', taxa)
new_time = _check_time(start, 'Validation')
fit = ctx.get_action('feature_classifier', 'fit_classifier_naive_bayes')
classify = ctx.get_action('feature_classifier', 'classify_sklearn')
_eval = ctx.get_action('rescript', 'evaluate_classifications')
# Deploy perfect classifier! (no CV, lots of data leakage)
classifier, = fit(reference_reads=sequences,
reference_taxonomy=taxonomy)
new_time = _check_time(new_time, 'Training')
observed_taxonomy, = classify(reads=sequences,
classifier=classifier,
reads_per_batch=reads_per_batch,
n_jobs=n_jobs,
confidence=confidence,
read_orientation='same')
new_time = _check_time(new_time, 'Classification')
evaluation, = _eval([taxonomy], [observed_taxonomy])
_check_time(new_time, 'Evaluation')
_check_time(start, 'Total Runtime')
return classifier, evaluation, observed_taxonomy
def evaluate_cross_validate(ctx,
sequences,
taxonomy,
k=3,
random_state=0,
reads_per_batch='auto',
n_jobs=1,
confidence=0.7):
'''
taxonomy: FeatureData[Taxonomy] artifact of taxonomy labels
sequences: FeatureData[Sequence] artifact of sequences
k: number of kfold cv splits to perform.
random_state: random state for cv.
'''
# silence impertinent sklearn warnings:
# 1. classifier version (the classifier is not saved or reused)
# 2. class sizes (this is handled by taxonomic stratification/relabeling)
msg = 'The TaxonomicClassifier.*cannot be used with other versions'
filterwarnings("ignore", message=msg, category=UserWarning)
filterwarnings(
"ignore", message='The least populated class', category=UserWarning)
# Validate inputs
start = timeit.default_timer()
taxa, seq_ids = _validate_cross_validate_inputs(taxonomy, sequences)
new_time = _check_time(start, 'Validation')
fit = ctx.get_action('feature_classifier', 'fit_classifier_naive_bayes')
classify = ctx.get_action('feature_classifier', 'classify_sklearn')
_eval = ctx.get_action('rescript', 'evaluate_classifications')
# split taxonomy into training and test sets
train_test_data = _generate_train_test_data(taxa, k, random_state)
# now we perform CV classification
expected_taxonomies = []
observed_taxonomies = []
for n, (train_taxa, test_taxa) in enumerate(train_test_data):
train_ids = train_taxa.index
test_ids = test_taxa.index
train_seqs, test_seqs = _split_fasta(sequences, train_ids, test_ids)
ref_taxa = q2.Artifact.import_data('FeatureData[Taxonomy]', train_taxa)
new_time = _check_time(new_time, 'Fold {0} split'.format(n))
# TODO: incorporate different methods? taxonomic weights? params?
classifier, = fit(reference_reads=train_seqs,
reference_taxonomy=ref_taxa)
new_time = _check_time(new_time, 'Fold {0} fit'.format(n))
observed_taxonomy, = classify(reads=test_seqs,
classifier=classifier,
reads_per_batch=reads_per_batch,
n_jobs=n_jobs,
confidence=confidence,
read_orientation='same')
# compile observed + expected taxonomies for evaluation outside of loop
expected_taxonomies.append(test_taxa)
observed_taxonomies.append(observed_taxonomy.view(pd.Series))
new_time = _check_time(new_time, 'Fold {0} classify'.format(n))
# Merge expected/observed taxonomies
expected_taxonomies = q2.Artifact.import_data(
'FeatureData[Taxonomy]', pd.concat(expected_taxonomies))
observed_taxonomies = q2.Artifact.import_data(
'FeatureData[Taxonomy]', pd.concat(observed_taxonomies))
evaluation, = _eval([expected_taxonomies], [observed_taxonomies])
_check_time(new_time, 'Evaluation')
_check_time(start, 'Total Runtime')
return expected_taxonomies, observed_taxonomies, evaluation
def _check_time(old_time, name='Time'):
new_time = timeit.default_timer()
print('{0}: {1:.2f}s'.format(name, new_time - old_time))
return new_time
# input validation for cross-validation functions
def _validate_cross_validate_inputs(taxonomy, sequences):
taxa = taxonomy.view(pd.Series)
# taxonomies must have even ranks (this is used for confidence estimation
# with the current NB classifier; we could relax this if we implement other
# methods later on for CV classification).
_validate_even_rank_taxonomy(taxa)
seq_ids = {i.metadata['id'] for i in sequences.view(DNAIterator)}
_validate_index_is_superset(set(taxa.index), seq_ids)
return taxa, seq_ids
def _split_fasta(sequences, train_ids, test_ids):
'''
Split FeatureData[Sequence] artifact into two, based on two sets of IDs.
sequences: FeatureData[Sequence] Artifact
train_ids: set
test_ids: set
'''
train_seqs = DNAFASTAFormat()
test_seqs = DNAFASTAFormat()
with train_seqs.open() as _train, test_seqs.open() as _test:
for s in sequences.view(DNAIterator):
_id = s.metadata['id']
if s.metadata['id'] in train_ids:
_train.write('>%s\n%s\n' % (_id, str(s)))
elif s.metadata['id'] in test_ids:
_test.write('>%s\n%s\n' % (_id, str(s)))
train_seqs = q2.Artifact.import_data('FeatureData[Sequence]', train_seqs)
test_seqs = q2.Artifact.import_data('FeatureData[Sequence]', test_seqs)
return train_seqs, test_seqs
def evaluate_classifications(ctx,
expected_taxonomies,
observed_taxonomies,
labels=None):
volatility = ctx.get_action('longitudinal', 'volatility')
# Validate inputs.
if len(expected_taxonomies) != len(observed_taxonomies):
raise ValueError('Expected and Observed Taxonomies do not match. '
'Input must contain an equal number of expected and '
'observed taxonomies.')
labels = _process_labels(labels, expected_taxonomies)
# Do a quick iteration over input pairs to validate indices match.
# Why loop over twice? So this does not fail midway through computing
# results on a big batch of inputs if a user makes a mistake.
expected_taxonomies = [t.view(pd.Series) for t in expected_taxonomies]
observed_taxonomies = [t.view(pd.Series) for t in observed_taxonomies]
for n, (t1, t2) in enumerate(zip(
expected_taxonomies, observed_taxonomies), 1):
try:
_validate_index_is_superset(t1.index, t2.index)
except ValueError:
raise ValueError(
'Expected and Observed Taxonomies do not match. Expected '
'taxonomy must be a superset of observed taxonomies. Indices '
'of pair {0} do not match.'.format(n))
results = []
for t1, t2, name in zip(expected_taxonomies, observed_taxonomies, labels):
# Align Indices
expected_taxonomy, observed_taxonomy = t1.align(t2, join='inner')
# Evaluate classification accuracy
precision_recall = _calculate_per_rank_precision_recall(
expected_taxonomy, observed_taxonomy)
precision_recall['Dataset'] = str(name)
results.append(precision_recall)
precision_recall = pd.concat(results)
# convert index to strings
precision_recall.index = pd.Index(
[str(i) for i in range(1, len(precision_recall.index) + 1)], name='id')
plots, = volatility(metadata=q2.Metadata(precision_recall),
state_column='Level',
default_group_column='Dataset',
default_metric='F-Measure')
return plots
def _generate_train_test_data(taxonomy, k, random_state):
'''
taxonomy: pd.Series of taxonomy labels
k: number of kfold cv splits to perform.
random_state: random state for cv.
'''
skf = StratifiedKFold(n_splits=k, shuffle=True, random_state=random_state)
for train, test in skf.split(taxonomy.index, taxonomy.values):
# subset sequences and taxonomies into training/test sets based on ids
train_taxa = taxonomy.iloc[train]
test_taxa = taxonomy.iloc[test]
# Compile set of valid stratified taxonomy labels:
train_taxonomies = _get_valid_taxonomic_labels(train_taxa)
# relabel test taxonomy expected labels using stratified set
# If a taxonomy in the test set doesn't exist in the training set, trim
# it until it does
test_taxa = test_taxa.apply(
lambda x: _relabel_stratified_taxonomy(x, train_taxonomies))
yield train_taxa, test_taxa
def _get_valid_taxonomic_labels(taxonomy):
valid_labels = {
';'.join(t.split(';')[:level]) for t in taxonomy.unique()
for level in range(1, len(t.split(';'))+1)}
return valid_labels
def _relabel_stratified_taxonomy(taxonomy, valid_taxonomies):
'''
Relabel taxonomy label to match nearest valid taxonomic label.
taxonomy: str
valid_taxonomies: set
'''
t = taxonomy.split(';')
for level in range(len(t), 0, -1):
if ';'.join(t[:level]) in valid_taxonomies:
return ';'.join(t[:level]).strip()
else:
raise RuntimeError('unknown kingdom in query set: ' + taxonomy)
def _calculate_per_rank_precision_recall(expected_taxonomies,
observed_taxonomies):
max_depth = max(_taxonomic_depth(expected_taxonomies, "").max(),
_taxonomic_depth(observed_taxonomies, "").max())
precision_recall = []
for level in range(1, max_depth + 1):
exp = expected_taxonomies.apply(
lambda x: ';'.join(x.split(';')[:level]))
obs = observed_taxonomies.apply(
lambda x: ';'.join(x.split(';')[:level]))
p, r, f = _precision_recall_fscore(exp, obs)
precision_recall.append((level, p, r, f))
precision_recall = pd.DataFrame(
precision_recall,
columns=['Level', 'Precision', 'Recall', 'F-Measure'])
return precision_recall
# ported from q2_quality_control with permission of nbokulich
# this computes modified precision calculation: underclassifications count as
# false negatives at level L, but not as false positives.
def _precision_recall_fscore(exp, obs, sample_weight=None):
# precision, recall, fscore, calculated using microaveraging
if sample_weight is None:
sample_weight = [1]*len(exp)
tp, fp, fn = 0, 0, 0
for e, o, w in zip(exp, obs, sample_weight):
if o == e:
# tp for the true class, the rest are tn
tp += w
elif e.startswith(o) or o in (
'Unclassified', 'Unassigned', 'No blast hit', 'other'):
# fn for the true class
fn += w
# no fp for the predicted class, because it was right to some level
# the rest are tn
else:
# fp the the predicted class
fp += w
# fn for the true class, the rest are tn
fn += w
# avoid divide by zero error. If no true positives, all scores = 0
if tp == 0:
return 0, 0, 0
else:
p = tp / (tp + fp)
r = tp / (tp + fn)
f = 2.*p*r / (p + r)
return p, r, f
def _validate_even_rank_taxonomy(taxa):
'''
Check + raise error if taxonomy does not have 100% even taxonomic levels.
taxa: pd.Series of taxonomic labels.
'''
depths = taxa.str.count(';')
uniq_values = depths.unique()
if len(uniq_values) > 1:
max_value = max(uniq_values)
raise ValueError('Taxonomic label depth is uneven. All taxonomies '
'must have the same number of semicolon-delimited '
'ranks. The following features are too short: ' +
', '.join(depths[depths < max_value].index))
def _validate_indices_match(idx1, idx2):
'''
match indices of two pd.Index objects.
idx1: pd.Index
idx2: pd.Index or array-like
'''
diff = idx1.symmetric_difference(idx2)
if len(diff) > 0:
raise ValueError('Input features must match. The following features '
'are missing from one input: ' + ', '.join(diff))
def _validate_index_is_superset(idx1, idx2):
'''
match indices of two pd.Index objects.
idx1: pd.Index or array-like
idx2: pd.Index or array-like
'''
diff = idx2.difference(idx1)
if len(diff) > 0:
raise ValueError('The taxonomy IDs must be a superset of the sequence '
'IDs. The following feature IDs are missing from the '
'sequences: ' + ', '.join(diff))