Build a Product Taxonomy Classifier Across Inconsistent Labels
Machine LearningModel answerLast updated
Design a production ML system that assigns products to a noisy, multi-path category tree with consistent predictions, calibrated confidence, and sub-100ms latency.
Context
An e-commerce platform maintains a category tree for its product catalog. The tree has roughly 10,000 nodes, a depth of 5–7 levels, and a heavy long tail: the top 1% of nodes account for more than half of all labeled products.
Merchants tag their own products, so the label data is noisy. Tags are missing at some levels, contradictory at others, and use non-canonical synonyms throughout. A single product can legitimately belong to multiple paths through the tree — a ceramic mug gift set belongs under both Home > Kitchen > Drinkware and Gifts > Gift Sets.
The system is used by several downstream consumers: search facets, tax and shipping logic, ads targeting, and recommendations. Each consumer has different tolerance for precision versus recall errors. Tax logic requires high precision. Discovery features tolerate more recall.
What you are being asked to design
Walk through the complete design of a classifier for this setting. Your answer should cover:
- Label space definition — is this multi-class or multi-label? What constraint must every output satisfy?
- Data cleaning and taxonomy normalization — how do you turn noisy merchant tags into usable training labels?
- Model architecture — what encoder, label representation, and dependency-modeling approach would you use?
- Loss function — how do you handle unknown descendants, easy-negative flood, and class imbalance?
- Thresholding and decoding — how do you produce a consistent, calibrated set of paths at inference time?
- Evaluation — what metrics capture both head and tail performance, and how do you give partial credit for near-miss predictions?
- Operational concerns — training data volume, online latency target, and monitoring strategy.
For each decision, state your recommendation and explain why you prefer it over the main alternatives.
Hints
Hint 1
Before touching models, nail down exactly what a valid output looks like. If a leaf node is predicted positive, what must be true about every node above it? This constraint shapes every later decision.
Hint 2
Merchant tags are often present at the leaf level but missing at intermediate levels, or vice versa. These partial paths are not negative labels for the missing nodes — treating them as negatives is one of the most common mistakes. Think about how you signal 'unknown' to the loss function.
Hint 3
Three approaches exist for enforcing hierarchy consistency: (1) model conditional probabilities top-down, (2) apply a post-hoc fix after a flat sigmoid, or (3) build consistency into the architecture with a max-constraint layer. Think through where each approach fails before picking one.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify the label space and output contract
This is a multi-label problem, not multi-class. A product can belong to multiple root-to-node paths. Within a single path it is effectively multi-class — exactly one node per level is correct — but across paths a product can have several valid ones.
Every output must satisfy the true-path rule: if a node is predicted positive, all of its ancestors must also be positive. A prediction set that violates this is internally inconsistent and will break downstream consumers.
State the output contract before discussing any model: the system returns a set of consistent paths, each with a calibrated confidence score. A path may terminate at an internal node when confidence for deeper levels falls below threshold. Predicting "Apparel > Shoes" when the subcategory is ambiguous is a better failure mode than predicting a wrong leaf.
Two serving modes follow from this:
- Online: under 100ms p99 when a merchant creates a product.
- Batch: nightly backfill when the taxonomy is updated.
2. Data cleaning and taxonomy normalization
This step usually has more impact than the model choice.
Canonicalize tags. Lowercase, lemmatize, apply a synonym dictionary ("tee" → "T-Shirts"), then embed tag strings and node names and match by nearest neighbor. Tags with low similarity to any node go to a human review queue. Version the taxonomy and maintain old-to-new node mappings so existing labels survive taxonomy edits.
Apply ancestor closure. If a product is tagged with a child node but not its parent, add the parent. This single rule fixes the majority of cross-level inconsistencies.
Handle partial paths correctly. If a product is tagged with a parent but no child, the child label is unknown, not negative. Masking those nodes in the loss — setting their gradient contribution to zero — is the most important cleaning decision in the entire pipeline. Training on false negatives here degrades recall on common paths.
Resolve contradictions. When siblings that should be mutually exclusive are both tagged (e.g., "Men's" and "Women's"), resolve by majority vote across signals — merchant tag, product type field, marketplace category — weighted by per-merchant reliability estimated on a gold set. Drop products with unresolved conflicts from training rather than keeping noisy labels.
Prevent leakage. Near-duplicate products from the same merchant should be deduplicated. Split train and evaluation sets by merchant, not by product, so the model cannot memorize merchant-specific styles.
3. Model architecture
Encoder. Use a multilingual distilled transformer over the concatenated title, product type, vendor, and tags. Add a CLIP or ViT embedding for product images. Fuse with an MLP to produce a 512-dimensional item vector h.
Label representation. Give each of the 10,000 nodes a learnable embedding e_k, initialized from the text encoding of its full path name (e.g., "Home > Kitchen > Drinkware"). The logit for node k is z_k = h · e_k + b_k. This is a single matrix multiply at inference, shares statistical strength across related nodes, and gives new nodes a reasonable zero-shot prior from their names.
Enforcing hierarchy consistency. Three options exist:
- Top-down conditional: model p(child | parent). Consistent by construction, but upper-level errors cascade irreversibly downward.
- Flat sigmoid + post-hoc fix: simple to implement, but violations must be corrected after the fact, and the model never learns the constraint.
- Max-constraint layer (C-HMCNN style): p̂(parent) = max(p(parent), max over descendants). Consistent by construction, no cascade, negligible compute overhead. This is the default choice.
For catalogs growing past ~50k nodes, switch to a two-stage pipeline: ANN retrieval over label embeddings shortlists ~200 candidates, then a cross-encoder reranks them.
4. Loss function
Base loss: masked binary cross-entropy across all nodes. Nodes with unknown labels (partial paths) receive mask = 0.
Constraint-aware loss (MCLoss): paired with the max-constraint layer, gradients for positive parent nodes flow through whichever descendant achieved the max. The model learns to explain parent membership through its children, which improves leaf-level recall.
Handling imbalance: each product has roughly 10,000 negative nodes and only 5–15 positives. Use asymmetric loss or focal loss (γ ≈ 2) to down-weight the flood of easy negatives. Optionally add per-node positive weights proportional to 1/√frequency for the long tail.
5. Thresholding and decoding
Calibrate using temperature scaling per depth level on a held-out set. For high-volume nodes, use isotonic regression per node. For tail nodes, back off to the parent level's calibrator to avoid overfitting a noisy held-out count.
Set per-node thresholds to match each consumer's operating point: precision ≥ 0.95 for tax-relevant nodes, best F1 elsewhere. Tail nodes inherit their parent's threshold.
Decode top-down:
- Expand a node only if its calibrated score exceeds its threshold.
- Allow multiple children for multi-label branches; use argmax for exclusive sibling groups.
- Stop at the deepest confident node.
Re-tune thresholds whenever the model is updated or the taxonomy changes.
6. Evaluation metrics
- Leaf level: micro-F1 (head-dominated), macro-F1 (tail-sensitive), precision@k, macro-averaged PR-AUC.
- Per-depth F1: reveals at which level errors originate.
- Hierarchical precision and recall: hP = Σ| ∩ A| / Σ|Â|, hR = Σ| ∩ A| / Σ|A|, combined into hF1. Here A and  are the ancestor-closed true and predicted sets. These metrics give partial credit for near-miss predictions — predicting "Apparel > Shoes" when the correct answer is "Apparel > Shoes > Sneakers" is penalized less than a completely wrong path.
- Per-consumer dashboards: track precision for tax nodes and recall for discovery nodes separately.
7. Training data and operations
Training data: tens of millions of merchant-tagged products after cleaning for weak supervision; a gold set of ~50k expert-labeled products stratified by level, locale, and merchant size. Aim for at least 50 clean positives per leaf node. Below that threshold, rely on label-embedding sharing and predict at the parent.
Active learning: route low-confidence predictions and newly added taxonomy nodes to annotators.
Monitoring: track label distribution shift (new nodes gaining volume, old nodes going stale), per-node F1 on a rolling sample, calibration error by depth, and merchant edit rate on suggestions as a behavioral precision signal. Retrain when any metric crosses a preset threshold.
Common mistakes to avoid
- Treating missing child labels as negatives rather than masking them.
- Using a flat threshold across all nodes — head nodes and tail nodes need different operating points.
- Evaluating only on leaf-level accuracy and missing that errors accumulate at upper levels.
- Forgetting to re-calibrate thresholds after a taxonomy update, even when the model weights do not change.