All posts
PythonFlaskNLPscikit-learnspaCy

ChefMate: NLP + ML Pipeline from User Input to Recipe

8 min readUpdated
Noisy ingredient text passes through normalization, fuzzy matching and recipe ranking to produce suggestions.
A simplified conceptual illustration of ingredient normalization and recipe recommendation. The examples illustrate processing stages rather than measured model outputs.
In this article · 11 sections

ChefMate starts with a practical question: what can someone cook with the ingredients they already have? That sounds like a recommendation problem, but much of the difficult work happens before ranking. Ingredient names arrive as plurals, regional names, multiword phrases and typing mistakes. A model cannot retrieve the right recipe consistently if the query and the recipe database disagree about what the same ingredient is called.

This walkthrough is based on the project's source inspected on October 20, 2026. It distinguishes the current implementation from improvements proposed below. In particular, the current training file uses CountVectorizer with cosine nearest-neighbour retrieval; describing that snapshot as a TF-IDF implementation would be inaccurate.

Define the retrieval contract

A useful response is more than a recipe name. It should show which requested ingredients matched, which ingredients are missing and what any displayed score means. A person choosing dinner can then decide whether buying two missing ingredients is acceptable.

The query can be represented as a set of canonical ingredient identifiers plus explicit filters for cuisine, diet and meal type. The output should retain stable recipe identifiers. Ranking may use vectors internally, but the user-facing explanation should come from identifiable ingredients rather than a mysterious similarity value.

I would keep “recipe coverage” separate from “query overlap.” If a user has tomato, onion, egg and rice, a recipe requiring tomato, onion and salt has two of three required ingredients available. Its coverage is about two thirds. That is different from the fraction of the user's four ingredients used by the recipe, and neither number is a probability that the dish will be good.

Normalize without erasing meaning

ChefMate's normalization helper lowercases text, uses spaCy lemmas, applies a curated synonym map and optionally performs fuzzy correction against known vocabulary. The source uses RapidFuzz, rather than the FuzzyWuzzy library named in an earlier description.

spaCy's lemmatizer documentation explains the role of lemmas and pipeline dependencies. In an ingredient search system, lemmatization is only one stage: it does not tell you that aubergine and eggplant are regional names for the same ingredient, or that coconut milk should remain distinct from ordinary milk.

Normalization needs a policy, not just a string-cleaning function. Preserve meaningful phrases, retain a mapping to the original text and make the same canonicalization rules apply during indexing and querying. If the database encodes green_onion while a synonym path returns green onion, splitting on whitespace changes one ingredient into two tokens. That is a representation inconsistency, not an issue a larger nearest-neighbour model will solve.

Fuzzy similarity is a candidate signal

The current helper accepts the best vocabulary match at a threshold of 80 on its similarity scale. That number is a rule in the source, not a measured accuracy percentage. RapidFuzz's documentation describes several scorers with different behavior; an arbitrary threshold does not have the same interpretation across all of them.

A short string deserves special caution. Two ingredient names can differ by only a few characters while referring to different foods. I would show uncertain corrections for confirmation, reject an empty vocabulary safely and compare the best match with the second-best match. A narrow gap is evidence of ambiguity even when the top score exceeds a threshold.

Keep fixtures for spelling errors that should be corrected and near-matches that must remain distinct. The cost of a wrong substitution can exceed the cost of returning fewer recipes. This article does not treat fuzzy text matching as an allergy or food-safety guarantee.

Understand the baseline before changing it

CountVectorizer creates a vocabulary and counts token occurrences. With cosine distance, nearest-neighbour search compares the direction of count vectors. The current training script fits that representation and a brute-force NearestNeighbors model, then persists the model, vectorizer and dataframe together.

Scikit-learn's feature-extraction guide distinguishes count-based features from TF-IDF weighting. TF-IDF can reduce the relative influence of terms common across many recipes, but that is a candidate experiment, not an automatic upgrade. Common ingredients may still matter to a user's ability to cook the dish.

Start with a transparent baseline such as ingredient-set overlap. Compare a binary count representation, ordinary counts and TF-IDF under the same test queries. Otherwise, a more complicated model may appear useful simply because it was compared against an undocumented or broken baseline.

A filtering bug that changes the meaning of an index

The inspected prediction code filters the recipe dataframe, resets its index and transforms those filtered rows into X. It then calls kneighbors on the previously fitted model, which was trained over the full dataset, and uses returned neighbour positions to select rows from the filtered dataframe. The computed filtered X is not used to fit that search.

Those positions refer to different collections. Imagine training rows [A, B, C, D] and a filter retaining [B, D]. A returned position 1 from the original model identifies B. Position 1 in the filtered dataframe identifies D. The code can therefore attach a distance to the wrong recipe, or discard a valid neighbour because its original position exceeds the filtered length.

This is a code-review finding, not a published fix to ChefMate. It illustrates a general rule: an index has meaning only relative to the collection that created it. Resetting dataframe indices does not remap an already fitted neighbour model.

Keep candidate rows and retrieval indices aligned

One correction strategy is to fit a candidate search over the filtered matrix. Another is to retrieve from the full index and apply filters using stable recipe identifiers, accepting that a fixed retrieval depth may miss eligible results. For a small dataset, the first option is easier to reason about.

Here is a standalone teaching example using an intentionally tiny corpus. It is not copied from the production application:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.neighbors import NearestNeighbors

recipes = [
    {"id": "r1", "diet": "vegetarian", "items": "tomato onion rice"},
    {"id": "r2", "diet": "other", "items": "chicken onion rice"},
    {"id": "r3", "diet": "vegetarian", "items": "egg tomato onion"},
]
vectorizer = CountVectorizer(binary=True)
matrix = vectorizer.fit_transform([row["items"] for row in recipes])
candidate_positions = [i for i, row in enumerate(recipes)
                       if row["diet"] == "vegetarian"]
candidate_matrix = matrix[candidate_positions]
search = NearestNeighbors(metric="cosine", algorithm="brute")
search.fit(candidate_matrix)
query = vectorizer.transform(["tomato onion"])
distances, local_positions = search.kneighbors(query, n_neighbors=2)
ranked_ids = [recipes[candidate_positions[i]]["id"]
              for i in local_positions[0]]
assert set(ranked_ids) == {"r1", "r3"}

In a real endpoint, check for an empty candidate set and an all-zero query vector before searching. Limit the neighbour count to the number of candidates. Those cases should return an understandable response rather than a library exception or an arbitrary ranking.

Make ranking and explanation agree

ChefMate exposes matched and missing ingredient lists and sorts results using an overlap score. That is a valuable explanation surface, but the definition should be consistent. Use sets of canonical ingredients for both numerator and denominator. Counting duplicate tokens in one part of the computation while deduplicating another can distort the score.

Separate retrieval from re-ranking explicitly. Cosine similarity can shortlist plausible recipes; a second stage can prioritize coverage, missing-item count or user preference. Keep those stages visible in debugging output. If a user sees a lower-coverage recipe above a higher-coverage one, you should be able to explain which ranking rule caused the order.

Avoid calling an overlap score “confidence.” It is a computed property of two sets, not a calibrated probability. A recipe can share most ingredients yet require a missing item essential to the dish.

Evaluate with query families and useful labels

Create a small judged query set before tuning thresholds. Include clean input, plurals, regional synonyms, misspellings, multiword ingredients, unseen terms, restrictive filters and empty input. Keep separate labels for canonicalization correctness and recipe relevance.

For ranking, Precision@k measures how many returned items are judged relevant. Recall@k asks how many relevant items were recovered from the judged candidate universe. If relevance is graded, a ranking measure such as NDCG can reflect that a nearly cookable recipe is more useful than a weak match. Specify the relevance rubric; metrics without a labeling policy are difficult to interpret.

Prevent duplicate recipes from appearing in both tuning and evaluation sets. Record baseline results, then change one stage at a time. The earlier “70% improvement” claim had no accompanying benchmark in the material inspected, so I do not carry it forward as a measured result.

Persist the representation as one versioned unit

The persisted vectorizer, dataset and search model must describe the same vocabulary and row order. Add a schema version, dataset hash, dependency versions and normalization version to the artifact metadata. A model file that loads successfully can still be semantically incompatible with a new dataframe.

Scikit-learn's persistence documentation discusses compatibility and the risk of pickle-based loading. Treat model artifacts as trusted deployment inputs; do not deserialize files submitted by arbitrary users. Load the approved artifact once per worker rather than reopening a large file on every request, and measure memory use before adding more workers.

What I would improve next

I would fix index alignment first, then unify canonical ingredient identifiers and add normalization fixtures. Only after those changes would I compare count features with TF-IDF or embeddings. A stronger representation cannot compensate for selecting the wrong dataframe row.

The most reusable lesson is that retrieval quality depends on contracts between stages: canonicalization, candidate selection, vectorization, neighbour lookup and explanation. Testing those contracts makes a modest model easier to trust and a future model easier to evaluate.

Sources and implementation references

The small corpus and correction example are explanatory material. The proposed evaluation has not been presented here as a completed benchmark.