<jupyter_start><jupyter_text>Model (sklearn)  to Flask<jupyter_code>import pandas as pd
from sklearn.metrics.pairwise import euclidean_distances
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.neighbors import NearestNeighbors
df = pd.read_csv("data/candy.csv")
df = df[df['review'] >= 5]<jupyter_output><empty_output><jupyter_text>Prep for:<jupyter_code>df = pd.read_csv("data/candy.csv")
df = df[df['review'] >= 5]
df = df.groupby(["user"])["item"].apply(lambda x: ",".join(x))
df = pd.DataFrame(df)
df.head()<jupyter_output><empty_output><jupyter_text>Putting a bow on the Katacoda<jupyter_code>class NNRecommender:
    def __init__(self, n_neighbors=5, separator=","):
        self.separator = separator
        self.cv = CountVectorizer(tokenizer=lambda x: x.split(separator))
        self.nn = NearestNeighbors(n_neighbors=n_neighbors)
        
    def __repr__(self):
        return f'NNRecommender(n_neighbors={self.nn.n_neighbors}, separator="{self.separator}")'
        
    def fit(self, X):
        self.X = X
        X = self.cv.fit_transform(X)
        self.nn.fit(X)
        return self

    def predict(self, X):
        Xp = []
        for Xi in X:
            Xt = self.cv.transform([Xi])
            neighbors = self.nn.kneighbors(Xt, return_distance=False)
            Y = []
            for n in neighbors[0]:
                y = self.X.iloc[int(n)].split(self.separator)
                Y.extend(y)
            Y = list(set(Y))
            Y = [y for y in Y if y not in Xi.split(self.separator)]
            Xp.append(Y)
        return Xp
model = NNRecommender(n_neighbors=5)
model.fit(df["item"])
df.sample(1)['item'].values
sweet = ["Airheads Xtremes Sweetly Sour Candy Rainbow Berry,Life Savers Five Flavor Gummies,Twizzlers Pull-N-Peel Candy Cherry"]
peanut = ["Reese's Peanut Butter Cups Miniatures,M&Ms Peanut Chocolate Candy,Reese's Peanut Butter Big Cup"]
model.predict(sweet)
model.predict(peanut)
import cloudpickle
with open("model.pkl", "wb") as f:
    cloudpickle.dump(model, f)
del model
with open("model.pkl", "rb") as f:
    model = cloudpickle.load(f)
model.predict(peanut)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1329026303645593, 'fraction_numerical': 0.0027688047992616522, 'mean_word_length': 3.4701030927835053, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '368667', 'license': 'MIT', 'n_tokens_mistral': 813, 'n_tokens_neox': 766, 'n_words': 159, 'path': 'model.ipynb', 'repo_name': 'maxhumber/ODSC', 'size': '2167'}