File size: 1,404 Bytes
2f1d41b
fa572b1
 
 
 
 
 
 
2f1d41b
 
 
fa572b1
 
2f1d41b
 
fa572b1
2f1d41b
 
 
 
 
fa572b1
 
 
 
2f1d41b
fa572b1
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Example for the Grocery Next model repository.

The model ranks complementary grocery items by smoothed co-occurrence.
Without a popularity penalty the ubiquitous staples (onions, garlic,
tomatoes, ...) dominate every answer, so the recommended default is
``popularity_penalty=8``. Pass 0 to see the raw association estimate.
"""

from grocery import GroceryModel

PENALTY = 8.0  # 0 = raw estimate, 8 = CLI default, higher = emphasize rarity

model = GroceryModel.load("model.json")

# Recommended: results track the selected items.
for selected in (
    ["tomatoes", "onions"],
    ["jasmine rice", "green curry paste"],
    ["injera", "berbere"],
):
    print(f"\nSelected: {', '.join(selected)}  (popularity_penalty={PENALTY})")
    for rank, prediction in enumerate(
        model.predict(selected, top_k=5, popularity_penalty=PENALTY), start=1
    ):
        print(f"{rank}. {prediction.item} ({prediction.score:.1%})")

# Why the penalty exists: the same input, raw vs. penalized.
selected = ["injera", "berbere"]
print(f"\nSame input, raw (popularity_penalty=0) vs. penalized ({PENALTY}):")
raw = model.predict(selected, top_k=5, popularity_penalty=0.0)
pen = model.predict(selected, top_k=5, popularity_penalty=PENALTY)
print("  raw:      " + ", ".join(f"{p.item} {p.score:.1%}" for p in raw))
print("  penalized: " + ", ".join(f"{p.item} {p.score:.1%}" for p in pen))