brunoamaral/gregory-ai/ml-engineer
Claude Code and agent skill by brunoamaral/gregory-ai
- community
Checking that the SKILL.md file is still in the repository.
Train, evaluate, debug, and extend GregoryAI's machine learning pipeline for article relevance prediction. Use this skill whenever someone asks about training models, running predictions, debugging ML issues, adding new algorithms, understanding prediction scores, pseudo-labeling, model versioning, or the ML consensus system. Triggers include questions like "train models for team X", "why is recall low", "add a new algorithm", "how does pseudo-labeling work", "run predictions", "check model metrics", "what does the ML pipeline do", or any work involving the gregory.ml module, train_models / predict_articles management commands, or the files_repo_PBL_nsbe research notebooks.
Install
npx vskill@latest install brunoamaral/gregory-ai/ml-engineerSKILL.md
ML Engineer for GregoryAI
Purpose
This skill covers the full ML lifecycle in GregoryAI: data collection, text preprocessing, model training (with optional pseudo-labeling), evaluation, model versioning, prediction, and the consensus system that determines article relevance.
Step 0 — Always read the source first
Before writing or modifying any ML code, read the relevant source files:
Read the files that are relevant to the task before making changes.
Architecture overview
Three algorithms
| Alias | Class | Module | Key artifacts | |
|---|---|---|---|---|
pubmed_bert | BertTrainer | gregory.ml.bert_wrapper | bert_weights.h5 | |
lgbm_tfidf | LGBMTfidfTrainer | gregory.ml.lgbm_wrapper | tfidf_vectorizer.joblib, lgbm_classifier.joblib | |
lstm | LSTMTrainer | gregory.ml.lstm_wrapper | lstm.weights.h5, tokenizer.json |
All three share a common interface:
Model storage
Artifacts live at:
Version format: YYYYMMDD, auto-incrementing _2, _3 etc. if a version already exists for the same day. Generated by gregory.utils.versioning.make_version_path().
Each version directory contains model weights/files plus metrics.json.
Key models in the database
MLPredictions— stores per-article, per-subject, per-algorithm prediction results
(predicted_relevant, probability_score, algorithm, subject, model_version)
PredictionRunLog— audit trail for every training and prediction run
(run_type='train'|'predict', team, subject, algorithm, model_version, metrics JSON, articles_processed)
ArticleSubjectRelevance— manual human labels (is_relevant boolean per article per subject)Subject.ml_consensus_type— determines how many algorithms must agree: 'any' (1), 'majority' (2), 'all' (3)Subject.auto_predict— whether automated predictions are enabled for this subject
Training pipeline
Managed by python manage.py train_models. The steps:
- Collect articles —
utils.dataset.collect_articles(team_slug, subject_slug)
filters Articles by team and subject, returns only those with human relevance labels.
- Build dataset —
utils.dataset.build_dataset(queryset)concatenates title + summary
into a 'text' column, maps is_relevant to 0/1.
- Summarise —
utils.summariser.summarise_bulk(texts)uses facebook/bart-large-cnn
with disk caching (MD5-keyed). Used during training to compress long texts.
- Split —
utils.dataset.train_val_test_split(df)does stratified 70/15/15 split.
Falls back to non-stratified if fewer than 3 samples per class.
- Pseudo-labeling (optional) —
gregory.ml.pseudo.generate_pseudo_labels()runs
iterative self-training: train on labeled data, predict unlabeled, add confident predictions (default threshold 0.9) back to training set, repeat up to max_iter=7.
- Train —
get_trainer(algo).train(...)with algorithm-specific defaults.
- Evaluate —
trainer.evaluate(test_texts, test_labels, threshold)returns
accuracy, precision, recall, f1, roc_auc, pr_auc, confusion_matrix.
- Save —
trainer.save(version_dir)writes model artifacts +metrics.json.
- Log — Creates a
PredictionRunLogentry with run_type='train'.
Command flags
Prediction pipeline
Managed by python manage.py predict_articles.
- Resolve model — finds the latest version directory for the given team/subject/algorithm.
- Load model — algorithm-specific loading logic:
- BERT: rebuild architecture then
load_weights(bert_weights.h5) - LGBM:
joblib.load()for vectorizer and classifier - LSTM: rebuild architecture, load weights + tokenizer JSON
- Select articles — unpredicted articles for this subject/algorithm combination,
within the lookback window (default 90 days, or --all-articles).
- Prepare text —
cleanHTML(title + ' ' + summary)thencleanText().
- Predict —
trainer.predict(texts, threshold)returns labels and probabilities.
- Store —
MLPredictions.objects.bulk_create()with article, subject, algorithm,
predicted_relevant, probability_score, model_version.
- Log — Creates a
PredictionRunLogentry with run_type='predict'.
Command flags
Consensus system
An article is considered "ML-relevant" for a subject when enough algorithms agree. The logic lives in api/filters.py → ArticleFilter._get_ml_relevant_articles_query():
- For each Subject with
auto_predict=True, read itsml_consensus_type. - Map consensus type to minimum algorithm count: any→1, majority→2, all→3.
- Find articles where at least that many distinct algorithms predicted relevant
with probability_score >= threshold.
- Union with manually-relevant articles (
ArticleSubjectRelevance.is_relevant=True).
The relevant=true filter parameter on the articles API triggers this logic. The ml_threshold parameter overrides the default 0.8 probability threshold.
Text preprocessing
Two layers of cleaning in gregory.utils.text_utils:
cleanHTML(text)— strips HTML tags via BeautifulSoupcleanText(text, min_words=10)— lowercases, removes DOI/PMID patterns,
removes stopwords, filters texts shorter than min_words
During training, summarise_bulk() compresses texts using BART-large-CNN. Summaries are cached to disk (MD5 hash key) so repeated training runs skip already-summarised articles.
GPU configuration
gregory.ml.gpu_config handles platform detection:
configure_gpu_memory_growth()— enables TF memory growth (Apple Silicon + NVIDIA)disable_gpu()— force CPU via environment variablesget_device_info()— returns dict with platform, GPU count, device list
The --cpu flag on management commands calls disable_gpu().
Algorithm-specific details
PubMed BERT (pubmed_bert)
- Base model:
microsoft/BiomedNLP-BiomedBERT-base-uncased-abstract-fulltext - Architecture: BERT → CLS token → Dense(48, ReLU, L2=0.01) → Dropout(0.3) → Dense(2, softmax)
- Default max_len: 400, learning_rate: 2e-5, batch_size: 16
- Early stopping: patience=3 on val_loss
- Supports pseudo-labeling via
perform_pseudo_labeling()method - Saves as HDF5 weights (
bert_weights.h5)
LightGBM + TF-IDF (lgbm_tfidf)
- TF-IDF: max_features=10000, min_df=2, max_df=0.95, ngram_range=(1,2)
- LightGBM: binary objective, gbdt boosting, 31 leaves, lr=0.05
- Early stopping: 10 rounds on validation loss
- Saves via joblib (vectorizer + classifier as separate files)
LSTM (lstm)
- TextVectorization: max_tokens=10000, sequence_length=100
- Architecture: Embedding(128) → Bidirectional LSTM(64) → Dropout(0.3) → Dense(1, sigmoid)
- Early stopping: patience=3 on val_loss
- Saves weights as
.weights.h5(Keras 3.x), tokenizer config as JSON
Research notebooks
The files_repo_PBL_nsbe/ directory contains the original research from the NovaSBE collaboration. Key resources:
model_documentation/— detailed docs for each algorithm classnotebooks_to_run/training_model.ipynb— end-to-end training notebooknotebooks_to_run/classification_of_articles.ipynb— inference notebooknotebooks_to_run/RNN_models_training_history/— LSTM experiment notebookscode_utils/— standalone implementations of all algorithms, pseudo-labeling, text processing
The Django wrappers (gregory.ml.*) are the production versions of these notebook implementations. When adding new algorithms or modifying existing ones, check both the wrapper and the original notebook/utility to understand the design intent.
Rules when modifying ML code
- Preserve the common trainer interface — any new algorithm must implement:
train(), evaluate(), predict(), save(), load(), export_metrics_json(). Register it in gregory.ml.trainer.get_trainer().
- Always log runs — create
PredictionRunLogentries for both training and prediction.
- Use the versioning system — call
make_version_path()for artifact storage.
Never overwrite existing version directories.
- Respect the consensus system — new algorithms participate in the consensus
count via MLPredictions records. Update consensus thresholds in Subject model if changing the algorithm count.
- Cache summaries — use
summarise_bulk()with caching enabled during training
to avoid redundant BART inference.
- Handle GPU gracefully — use
gpu_config.configure_gpu_memory_growth()at
startup. Support --cpu flag for environments without GPU.
- Threshold consistency — the default probability threshold is 0.8 across
training, prediction, and API filtering. Keep this consistent unless explicitly overridden.
- Test with small data first — use
--verbose 3and limit to a single
team/subject/algorithm when debugging.
- Metrics JSON — every saved model must include a
metrics.jsonwith val and
test metrics, model parameters, and training metadata.
- Text preparation — always apply
cleanHTML()thencleanText()before
prediction. During training, also apply summarise_bulk().
Debugging checklist
When predictions seem wrong or training fails:
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationWarning, 63 of 100Marginal. 1 run. Evaluated 8 months ago.
Source
- SKILL.md in the repositoryChecking.skills/ml-engineer/SKILL.md
Popularity
- Repository stars
- 57
- Repository forks
- 8
- 7-day trend score
- 20
Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 2 May 2026, 6 months ago.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/brunoamaral/gregory-ai/ml-engineer)