-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_rapids_classifier.py
More file actions
235 lines (193 loc) · 9.26 KB
/
run_rapids_classifier.py
File metadata and controls
235 lines (193 loc) · 9.26 KB
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
#!/usr/bin/env python3
"""
CLI entrypoints for training and prediction.
"""
import os
import sys
import argparse
from rich.console import Console
from rich.table import Table
console = Console()
def train_command(args):
console.print(f"[bold blue]Training Cell Type Classifier[/bold blue]")
if args.cv_folds < 0:
console.print("[red]Error: --cv-folds must be >= 0[/red]")
sys.exit(2)
if args.test_split is None or args.test_split < 0:
console.print("[red]Error: --test-split must be >= 0[/red]")
sys.exit(2)
if args.validation_split is None or args.validation_split < 0:
console.print("[red]Error: --validation-split must be >= 0[/red]")
sys.exit(2)
if not os.path.exists(args.input):
console.print(f"[red]Error: Input file {args.input} not found[/red]")
sys.exit(1)
console.print(f"[blue]Loading training data: {args.input}[/blue]")
##E Check anndata inputs
import anndata as ad
try:
adata_train = ad.read_h5ad(args.input)
except Exception as e:
console.print(f"[red]Error loading {args.input}: {e}[/red]")
sys.exit(1)
if args.label_key not in adata_train.obs.columns:
console.print(f"[red]Error: Label key '{args.label_key}' not found in .obs[/red]")
console.print(f"Available columns: {', '.join(adata_train.obs.columns)}")
sys.exit(1)
if args.feature_key not in adata_train.obsm.keys():
console.print(f"[red]Error: Feature key '{args.feature_key}' not found in .obsm[/red]")
console.print(f"Available keys: {', '.join(adata_train.obsm.keys())}")
sys.exit(1)
from lib.utils import prepare_adata
from config import classifier_default_values
from lib.rapids import RAPIDS_Classifier
feature_data, label_data = prepare_adata(
adata=adata_train,
label_key=args.label_key,
feature_key=args.feature_key
)
classifier = RAPIDS_Classifier()
os.makedirs(args.outdir, exist_ok=True)
optimisation_results_list = []
for model_type, default_params in classifier_default_values.items():
classifier.init_classifier(model_type=model_type, **default_params)
optimization_results = classifier.holdout_test_set_cv(
features_data=feature_data,
label_data=label_data,
test_size=args.test_split,
n_splits=args.cv_folds,
classifier_params=default_params,
param_grid=None,
use_optuna=True,
n_trials=args.optimization_trials,
optuna_direction="maximize",
)
print(f"Model type: {model_type}")
optimization_results["model_type"] = model_type
print(f"Optimization results: {optimization_results}")
optimisation_results_list.append(optimization_results)
### Get the best model type based on the optimization results
best_model_dict = max(optimisation_results_list, key=lambda x: x["test_score"])
best_model_type = best_model_dict["model_type"]
best_model_params = best_model_dict["best_params"]
best_model_test_score = best_model_dict["test_score"]
best_model_cv_scores = best_model_dict["cv_scores"]
best_model_avg_cv_score = best_model_dict["avg_cv_score"]
print(f"Best model type: {best_model_type}")
print(f"Best model params: {best_model_params}")
print(f"Best model test score: {best_model_test_score}")
print(f"Best model cv scores: {best_model_cv_scores}")
print(f"Best model avg cv score: {best_model_avg_cv_score}")
### Train the best model on the full dataset
classifier.init_classifier(model_type=best_model_type, **best_model_params)
classifier.train_full(
features_data=feature_data,
label_data=label_data,
model_type=best_model_type,
model_params=best_model_params,
)
classifier.save_status(args.outdir)
import json
with open(os.path.join(args.outdir, "optimization_results.json"), "w") as fh:
json.dump(best_model_dict, fh)
sys.exit(0)
def predict_command(args):
console.print(f"[bold blue]Cell Type Prediction[/bold blue]")
if not os.path.exists(args.model):
console.print(f"[red]Error: Model file {args.model} not found[/red]")
sys.exit(1)
if not os.path.exists(args.input):
console.print(f"[red]Error: Input file {args.input} not found[/red]")
sys.exit(1)
console.print(f"[blue]Loading model: {args.model}[/blue]")
from lib.rapids import RAPIDS_Classifier
from lib.utils import prepare_adata
import anndata as ad
import pandas as pd
classifier = RAPIDS_Classifier()
classifier.load_classifier(args.model)
classifier.load_encoder(args.encoder)
try:
adata_test = ad.read_h5ad(args.input)
except Exception as e:
console.print(f"[red]Error loading test data: {e}[/red]")
sys.exit(1)
feature_key = args.feature_key #or classifier.feature_names
if feature_key not in adata_test.obsm.keys():
console.print(f"[red]Error: Feature key '{feature_key}' not found in test data[/red]")
console.print(f"Available keys: {', '.join(adata_test.obsm.keys())}")
#console.print(f"Model was trained with: {classifier.feature_names}")
sys.exit(1)
features, _ = prepare_adata(adata_test, feature_key=args.feature_key, label_key=None)
### transform the features to model's
try:
predictions, pred_probs = classifier.get_predictions(features)
except Exception as e:
console.print(f"[red]Error during prediction: {e}[/red]")
sys.exit(1)
decoded_preds = classifier.get_decoded_labels(predictions).to_numpy()
pred_df = pd.DataFrame(
{
'label_pred': decoded_preds,
'label_pred_prob': pred_probs
},
index=adata_test.obs.index
)
output = ad.AnnData(
obs=pred_df,
uns={
'dataset_id': adata_test.uns.get("dataset_id", "unknown"),
'normalization_id': adata_test.uns.get("normalization_id", "unknown"),
'model_path': args.model,
'model_type': type(classifier.classifier).__name__,
'prediction_timestamp': pd.Timestamp.now().isoformat(),
},
)
os.makedirs(os.path.dirname(args.output) if os.path.dirname(args.output) else '.', exist_ok=True)
console.print(f"[blue]Writing results: {args.output}[/blue]")
table = Table(title="Prediction Summary")
table.add_column("Cell Type", style="cyan")
table.add_column("Count", style="magenta")
table.add_column("Percentage", style="green")
vc = pred_df['label_pred'].value_counts().sort_values(ascending=False)
total = len(pred_df)
cell_percentages = {}
for cell_type, count in vc.items():
percentage = f"{(count/total)*100:.1f}%"
cell_percentages[cell_type] = percentage
table.add_row(str(cell_type), f"{count:,}", percentage)
console.print(table)
output.uns["cell_percentages"] = cell_percentages
output.write_h5ad(args.output, compression="gzip")
output.obs.to_csv(args.output.replace(".h5ad", ".csv"))
import json
with open(args.output.replace(".h5ad", ".json"), "w") as fh:
json.dump(obj=output.uns, fp=fh, indent=4)
def main():
parser = argparse.ArgumentParser(description="RAPIDS-Accelerated Cell Type Annotation CLI")
subparsers = parser.add_subparsers(dest='command', help='Available commands')
train_parser = subparsers.add_parser('train', help='Train a cell type classifier')
train_parser.add_argument('-i', '--input', required=True, help='Input training h5ad file')
train_parser.add_argument('-o', '--outdir', required=True, help='Output folder to save classifier, data, encoder')
train_parser.add_argument('--label-key', default='label', help='Label column name in .obs (default: label)')
train_parser.add_argument('--feature-key', default='X_pca', help='Feature key in .obsm (default: X_pca)')
train_parser.add_argument('--optimization-trials', type=int, default=10, help='Number of Optuna trials (default: 10)')
train_parser.add_argument('--validation-split', type=float, default=0.1, help='Validation split fraction (default: 0.1, 0 = no validation)')
train_parser.add_argument('--test-split', type=float, default=0.0, help='Held-out test split fraction (default: 0; 0 disables test set)')
train_parser.add_argument('--cv-folds', type=int, default=0, help='Cross-validation folds (default: 0; 0/1 disables CV; >=2 enables CV)')
predict_parser = subparsers.add_parser('predict', help='Predict cell types')
predict_parser.add_argument('-i', '--input', required=True, help='Input test h5ad file')
predict_parser.add_argument('-m', '--model', required=True, help='Trained classifier file (.pkl)')
predict_parser.add_argument('-e', '--encoder', required=True, help='Trained model file encoder (.pkl)')
predict_parser.add_argument('-o', '--output', required=True, help='Output h5ad file with predictions')
predict_parser.add_argument('--feature-key', help='Feature key in .obsm (uses training key if not specified)')
args = parser.parse_args()
if not args.command:
parser.print_help()
return
if args.command == 'train':
train_command(args)
elif args.command == 'predict':
predict_command(args)
if __name__ == "__main__":
main()