<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Evan Harris on Medium]]></title>
        <description><![CDATA[Stories by Evan Harris on Medium]]></description>
        <link>https://medium.com/@emitchellh?source=rss-2fc9b61cf1b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SNZodu6oxUfAbkA_OHswfw.png</url>
            <title>Stories by Evan Harris on Medium</title>
            <link>https://medium.com/@emitchellh?source=rss-2fc9b61cf1b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:14:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emitchellh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Better Sparse Retrieval: Extending BM25 with Subwords]]></title>
            <link>https://medium.com/@emitchellh/extending-bm25-with-subwords-30b334728ebd?source=rss-2fc9b61cf1b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/30b334728ebd</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[information-retrieval]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Evan Harris]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 22:32:11 GMT</pubDate>
            <atom:updated>2023-12-19T02:42:01.374Z</atom:updated>
            <content:encoded><![CDATA[<p>The concept of <a href="https://weaviate.io/blog/hybrid-search-explained">Hybrid Search</a> is having a moment in the wake of the popularity of <a href="https://en.wikipedia.org/wiki/Large_language_model">Large Language Models</a> (LLMs) and <a href="https://en.wikipedia.org/wiki/Prompt_engineering#Retrieval-augmented_generation">Retrieval Augmented Generation</a> (RAG). With the recent rise in open source and as-a-service vector databases, we see many of them either natively supporting or offering an explainer on how to manage hybrid search for text retrieval (<a href="https://www.elastic.co/search-labs/tutorials/search-tutorial/vector-search/hybrid-search">here</a>, <a href="https://www.pinecone.io/learn/hybrid-search-intro/">here</a>, <a href="https://learn.microsoft.com/en-us/azure/search/hybrid-search-overview">here</a>, <a href="https://qdrant.tech/articles/hybrid-search/">here</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtJaZwcJf8m8M0mMYlN9oA.png" /><figcaption>Information retrieval in action</figcaption></figure><p>Ensembles of sparse and dense retrieval methods are <a href="https://link.springer.com/chapter/10.1007/978-3-540-68234-9_41">not new</a>. However, much of the <a href="https://python.langchain.com/docs/integrations/retrievers/weaviate-hybrid">tooling</a> is. Additionally, <a href="https://www.cs.otago.ac.nz/homepages/andrew/papers/2014-2.pdf">it has been shown</a> that the <a href="https://en.wikipedia.org/wiki/Okapi_BM25">BM25 ranking function</a> is an improvement over <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html">TF-IDF </a>.</p><p>A downside of a naive implementation of BM25 is the lack of attention to <a href="https://d2l.ai/chapter_natural-language-processing-pretraining/subword-embedding.html">subwords</a>. As the <a href="https://pypi.org/project/rank-bm25/">rank_bm25</a> python package suggests:</p><blockquote>Note that this package doesn’t do any text preprocessing. If you want to do things like lowercasing, stopword removal, stemming, etc, you need to do it yourself.</blockquote><blockquote>The only requirements is that the class receives a list of lists of strings, which are the document tokens.</blockquote><p>A query that references the key word ensembling will not match a potential target containing the word ensemble. Similarly, mismatched plurals, possessives, verb tenses, etc. will not result in retrieval hits as might be expected.</p><p>Common solutions are:</p><ol><li><a href="https://towardsdatascience.com/stemming-vs-lemmatization-2daddabcb221">Stemming or lemmatization</a>: Top down algorithms that convert words to their root form to be used as tokens.</li><li><a href="https://sh-tsang.medium.com/review-fasttext-enriching-word-vectors-with-subword-information-bafac50f22a8">Splitting at the subword level</a>: Tokenization techniques that use parts of words as unique tokens.</li><li><a href="https://www.datasciencebyexample.com/2022/01/15/2022-01-15-1/">Character n-grams</a>: Splitting at the character level and including n-gram sets of unique characters as tokens.</li></ol><p>Fans of <a href="https://fasttext.cc/">fasttext</a>, <a href="https://scikit-learn.org/">sklearn</a> and <a href="https://github.com/openai/tiktoken">LLM tokenization</a> may be more inclined to avoid top down techniques like lemmatization in favor of subwords or character n-grams. In short: throw tokens at the model, let it sort it out — don’t let the preprocessing be too opinionated.</p><h3>Improvement</h3><p>Here is a quick improvement over naive BM25 that utilizes the <a href="https://pypi.org/project/rank-bm25/">tiktoken</a> package from <a href="https://openai.com/">OpenAI</a>:</p><pre>import tiktoken<br><br>from typing import List<br><br>encoder = tiktoken.encoding_for_model(&quot;gpt-4&quot;)<br><br><br>def preprocess_func(text: str) -&gt; List[str]:<br>    # Lowercase the input text<br>    lowered = text.lower()<br><br>    # Convert the lowered text into tokens<br>    tokens = encoder.encode(lowered)<br><br>    # Stringify the tokens <br>    return [str(token) for token in tokens]</pre><p>While this may lose some advantages of using the raw text (coverage of out-of-vocabulary language), it is trivial to implement and leverages the power of <a href="https://openai.com/research/gpt-4">GPT-4’s</a> tokenization which handles subwords. An added benefit is that GPT-4 is multilingual, where techniques like lemmatization are typically language specific.</p><p>For example:</p><pre>&gt;&gt;&gt; preprocess_func(&quot;Indemnification&quot;)<br>[&#39;485&#39;, &#39;336&#39;, &#39;77&#39;, &#39;2461&#39;]<br><br>&gt;&gt;&gt; preprocess_func(&quot;indemnify&quot;)<br>[&#39;485&#39;, &#39;336&#39;, &#39;77&#39;, &#39;1463&#39;]<br><br>&gt;&gt;&gt; preprocess_func(&quot;indemnifies&quot;)<br>[&#39;485&#39;, &#39;336&#39;, &#39;77&#39;, &#39;9803&#39;]</pre><p>There is 75% overlap between these 3 terms which otherwise would have 0% overlap when splitting on full words.</p><p>Given a user query: Is there an indemnification clause?, it’s reasonable to expect a target like this to match:</p><blockquote>You will defend, <strong>indemnify</strong>, and hold harmless us, our affiliates and licensors, and each of their respective employees, officers, directors, and representatives from and against any Losses arising out of or relating to any third-party claim concerning: (a) your or any End Users’ use of the Services (including any activities under your AWS account and use by your employees and personnel); (b) breach of this Agreement or violation of applicable law by you, End Users or Your Content; or (c) a dispute between you and any End User.</blockquote><p>Some applications might perform just as well leaning on the dense semantic search component of a hybrid search system to incorporate subword information. Nonetheless, this remains a straightforward way to achieve lift in the sparse component of the system.</p><h3>Experiment</h3><p>Here are results from a few iterations with a private evaluation set. The evaluation set contains a mix of simple and challenging retrieval tasks with legal contracts (hundreds of examples):</p><pre>| Method                                             | recall@10 | recall@30 |<br>|----------------------------------------------------|-----------|-----------|<br>| Baseline                                           | 0.57      | 0.73      |<br>| Lowercasing                                        | 0.68      | 0.82      |<br>| Lowercasing + tiktoken encoding                    | 0.73      | 0.87      |<br>| Lowercasing + tiktoken encoding + stop word removal| 0.75      | 0.88      |</pre><p>This implementation utilizes the <a href="https://python.langchain.com/docs/integrations/retrievers/bm25">BM25Retriever</a> in the <a href="https://www.langchain.com/">LangChain</a> package by passing in a custom preprocess_func. The largest gain comes from lowercasing. We see additional lift by progressively layering on more techniques.</p><h3>Appendix</h3><p>As a bonus, the above experiment includes a pass with a multilingual stop word remover. It utilizes the <a href="https://pypi.org/project/stop-words/">stop-words</a> and <a href="https://pypi.org/project/langdetect/">langdetect</a> packages. Here is the implementation:</p><pre>from stop_words import get_stop_words<br>from langdetect import detect<br><br><br>def remove_multilingual_stopwords(text: str) -&gt; str:<br>    # Detect the language of the text<br>    try:<br>        lang = detect(text)<br>    except:<br>        return text<br><br>    # Get the list of stop words for the detected language<br>    try:<br>        stop_words = set(get_stop_words(lang))<br>    except:<br>        return text<br><br>    # Split the text into words and remove<br>    words = text.split()<br>    filtered_words = [word for word in words if word.lower() not in stop_words]<br><br>    # Reconstruct the text from filtered words<br>    return &quot; &quot;.join(filtered_words)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30b334728ebd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predict with sklearn 20x faster]]></title>
            <link>https://medium.com/building-ibotta/predict-with-sklearn-20x-faster-9f2803944446?source=rss-2fc9b61cf1b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f2803944446</guid>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Evan Harris]]></dc:creator>
            <pubDate>Tue, 25 Feb 2020 22:44:30 GMT</pubDate>
            <atom:updated>2020-02-26T14:48:32.931Z</atom:updated>
            <content:encoded><![CDATA[<p>At <a href="https://medium.com/building-ibotta">Ibotta</a> we deploy a lot of <a href="https://en.wikipedia.org/wiki/Machine_learning">machine learning</a> (ML) models. We use a number of technologies including <a href="https://medium.com/building-ibotta/ibottas-recommender-system-7a4034773bf9">Spark</a> for <a href="https://medium.com/building-ibotta/feature-engineering-at-ibotta-9a0454ce2961">batch</a> and <a href="https://medium.com/building-ibotta/powering-a-search-engine-with-amazon-sagemaker-43d91adad7be">Amazon SageMaker</a> for <a href="https://medium.com/building-ibotta/heating-up-word2vec-blazingtext-for-real-time-search-c2121bd1396">realtime</a>. While we’ve written in the past about <a href="https://medium.com/building-ibotta/reg2vec-learning-embeddings-for-high-cardinality-customer-registration-features-faf712f12842">some</a> <a href="https://medium.com/building-ibotta/ibottaml-better-faster-smaller-features-with-word2vec-c8bd72404ba6">of</a> <a href="https://medium.com/building-ibotta/erupt-expected-response-under-proposed-treatments-ff7dd45c84b4">our</a> <a href="https://medium.com/building-ibotta/estimating-and-visualizing-business-tradeoffs-in-uplift-models-80ff845a5698">use</a> <a href="https://medium.com/building-ibotta/multiple-responses-in-a-b-testing-1f7db3346c66">cases</a> and <a href="https://medium.com/building-ibotta/train-sklearn-100x-faster-bec530fc1f45">open source packages</a> for training models, this post is all about prediction.</p><p>As we’ve taken ML out of the <a href="https://aws.amazon.com/big-data/datalakes-and-analytics/what-is-a-data-lake/">data lake</a> (batch prediction) and into the <a href="https://martinfowler.com/articles/microservices.html">microservices</a> ecosystem (on-demand prediction) we’ve primarily utilized <a href="https://aws.amazon.com/sagemaker/">Amazon SageMaker</a> to deploy realtime machine learning prediction services. This has served us well, as we heavily rely on <a href="https://scikit-learn.org/stable/"><em>scikit-learn</em></a>, <a href="https://www.tensorflow.org/"><em>TensorFlow</em></a>, <a href="https://pytorch.org/"><em>PyTorch</em></a><em>,</em> <a href="https://xgboost.readthedocs.io/en/latest/"><em>XGBoost</em></a> and <a href="https://fasttext.cc/"><em>fasttext</em></a> which are all supported by SageMaker.</p><p>In addition to migrating ML deployment to microservices, we’ve also been looking at <a href="https://aws.amazon.com/serverless/">serverless technology</a> to deploy microservices more generally. In considering what it would be like to deploy ML model prediction as serverless applications, a few things become clear:</p><ol><li>ML packages and their dependencies are too big</li><li>ML models artifacts are too big</li><li>ML prediction isn’t <em>too </em>slow<em>— </em>but faster is better</li><li>We often only want to predict one record per request</li></ol><p>These considerations motivated the exploration of slimming down machine learning prediction to a dedicated library. By converting prediction methods to pure Python, we can make predictions faster, dependency packages smaller, and model objects lighter weight. This doesn’t solve everything for serverless inference as some models will just be too big — but it’s a start.</p><h4>Introducing pure-predict</h4><p>We are excited to announce the launch of our open source project <a href="https://github.com/Ibotta/pure-predict">pure-predict</a>. The goal of the project is to speed up and slim down machine learning prediction applications. It is a foundational tool for serverless inference or small batch prediction with popular machine learning frameworks like <a href="https://scikit-learn.org/stable/"><em>scikit-learn</em></a> and <a href="https://fasttext.cc/"><em>fasttext</em></a>. It implements the predict methods of these frameworks in pure Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*7S8ZCKFvc49rzD3M4wP4KQ.png" /></figure><p>The primary benefit of pure-predict is illustrated by the relative size of the package compared to <em>scikit-learn</em> and its dependencies. Here is <em>scikit-learn</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*O1nCczAiiGOrkojGnGHJQw.png" /></figure><p>All in all, <strong>255.9MB</strong>. In total, pure-predict is <strong>3.6MB</strong> — keeping in mind that it has <em>zero</em> dependencies outside of <a href="https://docs.python.org/3/library/functions.html">Python built-ins</a>.</p><p>As far as container services go, here are some <a href="https://developers.redhat.com/blog/2016/02/24/10-things-to-avoid-in-docker-containers/">notes on docker image sizes</a>. From the post:</p><pre><strong>Don’t create large images</strong> – A large image will be harder to distribute. Make sure that you have only the required files and libraries to run your application/process.</pre><p>Consider how many files and libraries are contained in <em>scikit-learn</em> and all of its dependencies that have nothing to do with the <em>predict()</em> method of any given <em>scikit-learn </em>estimator.</p><p>As far as serverless goes, here are some <a href="https://hackernoon.com/exploring-the-aws-lambda-deployment-limits-9a8384b0bec3">notes on AWS Lambda deployment package limitations</a>. From the post:</p><pre><strong>250 MB</strong>: <em>Size of code/dependencies that you can zip into a deployment package (uncompressed .zip/.jar size)</em></pre><p>There are indeed <a href="https://stackoverflow.com/questions/54632009/how-to-increase-the-maximum-size-of-the-aws-lambda-deployment-package-requesten">strategies to reduce the size of deployment packages</a> but <em>scikit-learn</em> and its dependencies are pushing the limit here. Regardless of workarounds, <a href="https://mikhail.io/serverless/coldstarts/aws/">large deployment packages can cause serverless functions to be 5–10 times slower at cold start</a>. This could be problematic depending on the access patterns and SLAs of the service.</p><p>Therein lies the motivation for pure-predict. As shown below, package size is only one of the benefits. We can achieve large performance improvements across a variety of metrics with pure Python implementations of ML prediction methods.</p><h4>Example</h4><p>In an environment with <em>scikit-learn</em> and it’s dependencies installed we can train a model, convert it to a pure-predict object, and save the object to disk:</p><pre>import pickle<br><br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.datasets import load_iris<br>from pure_sklearn.map import convert_estimator<br><br># fit sklearn estimator<br>X, y = load_iris(return_X_y=True)<br>clf = RandomForestClassifier()<br>clf.fit(X, y)<br><br># convert to pure python estimator<br>clf_pure_predict = convert_estimator(clf)<br>with open(&quot;model.pkl&quot;, &quot;wb&quot;) as f:<br>    pickle.dump(clf_pure_predict, f)</pre><p>In an environment with <em>only</em> Python and pure-predict installed, we can load the model into memory and make predictions:</p><pre>import pickle<br><br># load pickled model<br>with open(&quot;model.pkl&quot;, &quot;rb&quot;) as f:<br>    clf = pickle.load(f)<br><br># make prediction with pure-predict object<br>y_pred = clf.predict([[0.25, 2.0, 8.3, 1.0]])<br>print(y_pred)<br>[2]</pre><p>This is a trivial example — but consider <a href="https://github.com/Ibotta/pure-predict/blob/master/examples/performance_text_pipeline.py">this example in the github repository</a>. This is a model trained on 2 categories (<em>rec.autos</em>, <em>sci.space</em>) of the <a href="http://qwone.com/~jason/20Newsgroups/">20 newsgroups dataset</a>. A <a href="https://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html#extracting-features-from-text-files">text extraction</a> <a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html">pipeline</a> is constructed that <a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.FeatureUnion.html">unions</a> a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html"><em>TfidfVectorizer</em></a> and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.HashingVectorizer.html"><em>HashingVectorizer</em></a><em> (not recommended to union both of these in practice — though useful to illustrate performance)</em>. This <a href="https://www.kaggle.com/learn/feature-engineering">feature engineering</a> pipeline is chained to a full depth <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html"><em>RandomForestClassifier</em></a> with 100 estimators. Here are the comparison statistics between the <em>scikit-learn</em> version of the pipeline and the <em>pure_sklearn</em> version of the pipeline:</p><pre>Pickle Size sklearn: 5.55 MB<br>Pickle Size pure-predict: 3.33 MB<br>Difference: 0.60</pre><pre>Unpickle time sklearn: 0.0482<br>Unpickle time pure-predict: 0.0376<br>Difference: 0.78</pre><pre>Predict 1 record sklearn: 0.0942<br>Predict 1 record pure-predict: 0.0043<br>Difference: 0.05</pre><p>The <em>pure_sklearn</em> model is 60% of the size of its <em>scikit-learn</em> equivalent. This is valuable for serverless cold start or container size. It un-pickles (loads into memory from disk and deserializes) in 78% of the time of its <em>scikit-learn</em> equivalent. Again, valuable for serverless cold start. Finally, it predicts in <strong>5%</strong> of the time of its <em>scikit-learn</em> equivalent for single record prediction. This is particularly important as 94ms request latency and 4ms request latency can be the difference between a service that is viable in certain microservices ecosystems and one that isn’t.</p><p>An important caveat here is that this performance comparison won’t hold for all models in all situations. Trees are particularly performant with <em>pure_sklearn.</em> Linear models with wide feature spaces and a large n-classes will be less so (they benefit from the economies of scale with array operations in <em>numpy</em>) and will underperform <em>scikit-learn</em> as n-classes and n-features grows. In all cases, as the size of n-samples for prediction grows, all pure-predict models will underperform.</p><h4>Features</h4><p>At launch time, pure-predict contains two subpackages: <a href="https://github.com/Ibotta/pure-predict/tree/master/pure_sklearn"><em>pure_sklearn</em></a> and <a href="https://github.com/Ibotta/pure-predict/tree/master/pure_fasttext"><em>pure_fasttext</em></a>. The <em>pure_sklearn</em> package parallels <em>scikit-learn</em> for a number of estimators and transformers. A fitted <em>scikit-learn </em>estimator, pipeline or transformer can be converted into a <em>pure_sklearn</em> object. This object can then make predictions without <em>scikit-learn</em> and it’s dependencies. <strong>Note that <em>pure_sklearn</em> also supports </strong><a href="https://xgboost.readthedocs.io/en/latest/"><strong><em>XGBoost</em></strong></a><strong> models fit with the </strong><a href="https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.sklearn"><strong><em>scikit-learn</em> API</strong></a><strong>.</strong></p><p>The <em>pure_fasttext</em> package functions similarly. For <a href="https://github.com/facebookresearch/fastText/blob/master/docs/unsupervised-tutorials.md">unsupervised</a> mode, it handles vector lookups for words and sentences. For <a href="https://github.com/facebookresearch/fastText/blob/master/docs/supervised-tutorial.md">supervised</a> mode, it handles predictions.</p><h4>How It Works</h4><p>The implementation approach for pure-predict is very much brute force. Predict methods for various estimators are literally re-written in pure Python. Here is an example for a <a href="https://github.com/Ibotta/pure-predict/blob/master/pure_sklearn/tree/_classes.py">decision tree classifier from pure-predict</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*A2esyEIreb3CMHl8ZuuPnw.png" /></figure><p>This function returns the leaf node for any input x, where x is one record to predict (either a <a href="https://github.com/Ibotta/pure-predict/blob/master/pure_sklearn/utils.py#L122">sparse_list</a> or a list of floats). This is the guts of the prediction method for a decision tree. This is ported to pure Python directly from the <em>scikit-learn</em> <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/_tree.pyx">implementation</a> which uses <a href="https://cython.org/"><em>Cython</em></a> and <em>numpy</em> to achieve the same result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*ipI0UeUr6ajsvBpdfGOYmA.png" /></figure><p>By porting this to pure Python, we get the same functionality without the <em>numpy</em> dependencies and <em>Cython</em> implementation. While these certainly speed up training and prediction with many samples, they are generally slower for single record prediction. Additionally they require &gt;200MB of <em>numpy</em> and <em>scipy</em> in order to run.</p><p>Other methods were considered for slimming down package sizes. One idea would be to take any given fitted <em>scikit-learn</em> estimator and strip away unused modules in <em>scikit-learn</em>, <em>numpy </em>or <em>scipy.</em> This is doable with <em>scikit-learn</em>, as you can typically identify modules of the <em>scikit-learn</em> package that aren’t being used by any given estimator (for example, a random forest doesn’t need code in the <a href="https://scikit-learn.org/stable/modules/linear_model.html">linear_models</a> module). However, it gets more challenging once you drill down into <em>numpy</em> and <em>scipy</em> and their various cross-dependencies with each other and with <em>scikit-learn.</em></p><p>Ultimately, the brute force approach of porting prediction methods to pure Python was the chosen direction.</p><h4>Use Cases</h4><p>The primary use case for pure-predict is spelled out in more detail <a href="https://github.com/Ibotta/pure-predict/blob/master/README.rst#primary-use-cases">in the README</a>. It largely involves training a model in an offline environment, converting the fitted model to a pure-predict object and <a href="https://docs.python.org/3/library/pickle.html">pickling</a>, and finally deploying the pure-predict model in a serverless function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19pvbdoBNxbNqjdq3_uSzg.png" /></figure><p>Other use cases are for speeding up specific applications (serverless or otherwise) that roughly meet these criteria:</p><ol><li>Single record or small batch prediction</li><li><a href="https://scikit-learn.org/stable/modules/tree.html">Trees</a> (<a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html">decision tree</a>, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">random forest</a>, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html">gradient boosted trees</a>, etc.), <a href="https://scikit-learn.org/stable/modules/linear_model.html">linear</a> or <a href="https://scikit-learn.org/stable/modules/naive_bayes.html">bayesian</a> models with small n-classes/n-features, and <a href="https://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html">text extraction</a> pipelines</li></ol><h4>Getting Started</h4><p>To get started with pure-predict, check out the <a href="https://github.com/Ibotta/pure-predict#installation">installation guide</a>. The code repository also contains a library of <a href="https://github.com/Ibotta/pure-predict/tree/master/examples">examples</a> to illustrate some of the use cases of pure-predict. <a href="https://github.com/Ibotta/pure-predict/blob/master/CODE_OF_CONDUCT.md">All are welcome</a> to submit issues and contribute to the project. Note the specific <a href="https://github.com/Ibotta/pure-predict#calls-for-contributors">calls for contributors</a> to get involved.</p><p>If these kinds of projects and challenges sound interesting to you, Ibotta is hiring! Check out our <a href="https://ibotta.com/careers">jobs page</a> for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f2803944446" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-ibotta/predict-with-sklearn-20x-faster-9f2803944446">Predict with sklearn 20x faster</a> was originally published in <a href="https://medium.com/building-ibotta">Building Ibotta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Train sklearn 100x faster]]></title>
            <link>https://medium.com/building-ibotta/train-sklearn-100x-faster-bec530fc1f45?source=rss-2fc9b61cf1b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bec530fc1f45</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Evan Harris]]></dc:creator>
            <pubDate>Thu, 29 Aug 2019 19:30:10 GMT</pubDate>
            <atom:updated>2019-08-30T16:08:14.668Z</atom:updated>
            <content:encoded><![CDATA[<p>At Ibotta we train a lot of machine learning models. These models power our recommendation system, search engine, pricing optimization engine, data quality, and more. They make predictions for millions of users as they interact with our mobile app.</p><p>While we do much of our data processing with <a href="https://spark.apache.org/">Spark</a>, our preferred machine learning framework is <a href="https://scikit-learn.org/stable/">scikit-learn</a>. As compute gets cheaper and time to market for machine learning solutions becomes more critical, we’ve explored options for speeding up model training. One of those solutions is to combine elements from Spark and scikit-learn into our own hybrid solution.</p><h4>Introducing sk-dist</h4><p>We are excited to announce the launch of our open source project <a href="https://github.com/Ibotta/sk-dist">sk-dist</a>. The goal of the project is to provide a general framework for distributing scikit-learn meta-estimators with Spark. Examples of meta-estimators are decision tree ensembles (<a href="https://en.wikipedia.org/wiki/Random_forest">random forests</a> and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesClassifier.html">extra randomized trees</a>), <a href="https://scikit-learn.org/stable/modules/grid_search.html">hyperparameter tuners</a> (<a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV">grid search</a> and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html#sklearn.model_selection.RandomizedSearchCV">randomized search</a>) and multi-class techniques (<a href="https://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html#sklearn.multiclass.OneVsRestClassifier">one vs rest</a> and <a href="https://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsOneClassifier.html#sklearn.multiclass.OneVsOneClassifier">one vs one</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*Rz4L8-luiv481JtVFnHsIg.png" /></figure><p>Our primary motivation is to fill a void in the space of options for distributing traditional machine learning models. Outside of the space of neural networks and deep learning, we find that much of our compute time for training models is not spent on training a single model on a single dataset. The bulk of time is spent training multiple iterations of a model on multiple iterations of a dataset using meta-estimators like grid search or ensembles.</p><h4>Example</h4><p>Consider the <a href="https://scikit-learn.org/stable/auto_examples/classification/plot_digits_classification.html">hand written digits dataset</a>. Here we have encoded images of hand written digits to be classified appropriately. We can train a <a href="https://en.wikipedia.org/wiki/Support-vector_machine">support vector machine</a> on this dataset of 1797 records very quickly on a single machine. It takes under a second. But hyperparameter tuning requires a number of training jobs on different subsets of the training data.</p><p>Shown below, we’ve built a parameter grid totaling 1050 required training jobs. It takes only 3.4 seconds with sk-dist on a Spark cluster with over a hundred cores. The total task time of this job is 7.2 minutes, meaning it would take this long to train on a single machine with no parallelization.</p><pre>import time</pre><pre>from sklearn import datasets, svm<br>from skdist.distribute.search import DistGridSearchCV<br>from pyspark.sql import SparkSession </pre><pre># instantiate spark session<br>spark = (   <br>    SparkSession    <br>    .builder    <br>    .getOrCreate()    <br>    )<br>sc = spark.sparkContext </pre><pre># the digits dataset<br>digits = datasets.load_digits()<br>X = digits[&quot;data&quot;]<br>y = digits[&quot;target&quot;] </pre><pre># create a classifier: a support vector classifier<br>classifier = svm.SVC()<br>param_grid = {<br>    &quot;C&quot;: [0.01, 0.01, 0.1, 1.0, 10.0, 20.0, 50.0], <br>    &quot;gamma&quot;: [&quot;scale&quot;, &quot;auto&quot;, 0.001, 0.01, 0.1], <br>    &quot;kernel&quot;: [&quot;rbf&quot;, &quot;poly&quot;, &quot;sigmoid&quot;]<br>    }<br>scoring = &quot;f1_weighted&quot;<br>cv = 10</pre><pre># hyperparameter optimization<br>start = time.time()<br>model = DistGridSearchCV(    <br>    classifier, param_grid,     <br>    sc=sc, cv=cv, scoring=scoring,<br>    verbose=True    <br>    )<br>model.fit(X,y)<br>print(&quot;Train time: {0}&quot;.format(time.time() - start))<br>print(&quot;Best score: {0}&quot;.format(model.best_score_))</pre><pre>------------------------------<br>Spark context found; running with spark<br>Fitting 10 folds for each of 105 candidates, totalling 1050 fits<br>Train time: 3.380601406097412<br>Best score: 0.981450024203508</pre><p>This example illustrates the common scenario where fitting data into memory and training a single classifier is trivial but the number of required fits for hyperparameter tuning adds up quickly. Here is a look under the hood at running a grid search problem like the above example with sk-dist:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aMY7syLvvusX9EEW92ZgmA.png" /><figcaption>Grid Search with sk-dist</figcaption></figure><p>For real-world applications of traditional machine learning at Ibotta, we often find ourselves in a similar situation: small to medium sized data (100k to 1M records) with many iterations of simple classifiers to fit for hyperparameter tuning, ensembles and multi-class solutions.</p><h4>Existing Solutions</h4><p>There are existing solutions to distributing traditional machine learning meta-estimator training. The first is the simplest: scikit-learn’s built-in parallelization of meta-estimators using <a href="https://joblib.readthedocs.io/en/latest/">joblib</a>. This operates very similarly to sk-dist, except for one major constraint: performance is limited to the resources of any one machine. Even versus a theoretical single machine with hundreds of cores, Spark still has advantages like <a href="https://spark.apache.org/docs/latest/tuning.html">fine tuned memory specification for executors</a>, <a href="https://techvidvan.com/tutorials/fault-tolerance-in-spark/">fault tolerance</a>, as well as cost control options like using <a href="https://aws.amazon.com/ec2/spot/">spot instances</a> for worker nodes.</p><p>Another existing solution is <a href="https://spark.apache.org/docs/latest/ml-guide.html">Spark ML</a>. This is Spark’s native machine learning library, supporting many of the same algorithms as scikit-learn for classification and regression problems. It also has meta-estimators like tree ensembles and grid search, as well as support for multi-class problems. While this sounds like it may be a sufficient solution for distributing scikit-learn style machine learning workloads, it distributes training in a way that doesn’t solve the kind of parallelism of interest to us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TjK_ncABUrMGGf2OGxNFg.png" /><figcaption>Distributed on Different Dimensions</figcaption></figure><p>As shown above, Spark ML will train a single model on data that is distributed on many executors. This works well when data is large and won’t fit into memory on a single machine. However, when data is small this can <em>underperform</em> scikit-learn on a single machine. Furthermore, when training a random forest for example, Spark ML trains each decision tree in sequence. Wall time for this job will scale linearly with the number of decision trees regardless of the resources allocated to the job.</p><p>For <a href="http://spark.apache.org/docs/latest/api/python/pyspark.ml.html#pyspark.ml.tuning.CrossValidator">grid search, Spark ML</a> does implement a <a href="http://spark.apache.org/docs/latest/api/python/pyspark.ml.html#pyspark.ml.tuning.CrossValidator.parallelism">parallelism</a> parameter that will train <a href="https://issues.apache.org/jira/browse/SPARK-19357">individual models in parallel</a>. However each individual model is still training on data that is distributed across executors. The total parallelism of the job is a <a href="https://github.com/Ibotta/sk-dist/blob/master/examples/search/spark_ml.py">fraction of what it could be</a> if distributed purely along the dimension of models rather than data.</p><p>Ultimately, we want to distribute our training on a different dimension than that of Spark ML. When using small or medium data, fitting the data into memory is not a problem. For the random forest example, we want to broadcast the training data in full to each executor, fit an independent decision tree on each executor, and bring those fitted decision trees back to the driver to assemble a random forest. Distributing along this dimension can be <a href="https://github.com/Ibotta/sk-dist/blob/master/examples/search/spark_ml.py">orders of magnitude faster</a> than distributing the data and training decision trees in serial. This behavior is similar for other meta-estimator techniques like grid search and multi-class.</p><h4>Features</h4><p>Given the limitations of these existing solutions in our problem space, we decided to develop sk-dist in-house. The bottom line is that we want to <strong>distribute models, not data</strong>.</p><p>While the primary focus is on distributed training of meta-estimators, sk-dist also includes modules for distributed prediction of scikit-learn models with Spark, several pre/post processing scikit-learn transformers for use without Spark, and a flexible feature encoder for use with or without Spark.</p><ul><li><strong>Distributed Training</strong> — Distribute meta-estimator training with Spark. The following algorithms are supported: <a href="https://github.com/Ibotta/sk-dist/blob/master/skdist/distribute/search.py">Hyperparameter optimization</a> with grid search and randomized search, <a href="https://github.com/Ibotta/sk-dist/blob/master/skdist/distribute/ensemble.py">tree ensembles</a> with random forests, extra trees, and random trees embedding, and <a href="https://github.com/Ibotta/sk-dist/blob/master/skdist/distribute/multiclass.py">multi-class strategies</a> with one-vs-rest and one-vs-one. All of these meta-estimators mirror their scikit-learn counterparts after the fit.</li><li><strong>Distributed Prediction</strong> — <a href="https://github.com/Ibotta/sk-dist/blob/master/skdist/distribute/predict.py">Distribute the prediction methods</a> of fitted scikit-learn estimators with <a href="https://spark.apache.org/docs/latest/sql-programming-guide.html">Spark DataFrames</a>. This enables large scale distributed prediction with portable scikit-learn estimators that can be used with or without Spark.</li><li><strong>Feature Encoding</strong> — Distribute feature encoding with a flexible feature transformer called <a href="https://github.com/Ibotta/sk-dist/blob/master/skdist/distribute/encoder.py">Encoderizer</a>. It functions with or without Spark parallelization. It will infer data types and shapes, automatically applying default feature transformers as a best guess implementation of standard feature encoding techniques. It can also be used as a fully customizable feature union-like encoder with the added advantage of distributed transformer fitting with Spark.</li></ul><h4>Use Cases</h4><p>Here are some guidelines for deciding whether or not sk-dist is a good fit for your machine learning problem space:</p><ol><li><strong>Traditional Machine Learning</strong> — Methods like <a href="https://scikit-learn.org/stable/modules/linear_model.html">generalized linear models</a>, <a href="https://scikit-learn.org/stable/modules/sgd.html">stochastic gradient descent</a>, <a href="https://scikit-learn.org/stable/modules/neighbors.html">nearest neighbors</a>, <a href="https://scikit-learn.org/stable/modules/tree.html">decision trees</a>, and <a href="https://scikit-learn.org/stable/modules/naive_bayes.html">naive bayes</a> work well with sk-dist. These all have implementations in scikit-learn which are ready for direct implementation with sk-dist meta-estimators.</li><li><strong>Small to Medium Sized Data</strong> — Big data won’t work well with sk-dist. Keep in mind that the dimensionality of distribution of training is along the axis of the models, not the data. Data needs to not only fit in memory on each executor, but also be small enough to broadcast. Depending on Spark configuration, the maximum broadcast size can be limiting.</li><li><strong>Spark Orientation and Access</strong> — The core functionality of sk-dist requires running Spark. This isn’t always feasible for individuals or small data science teams. Additionally, some Spark tuning and configuration will be necessary to get the most out of sk-dist in a cost effective way, which requires some training in Spark fundamentals.</li></ol><p>An important note here is that while neural networks and deep learning could technically be used with sk-dist, these techniques require large amounts of training data and sometimes specialized infrastructure to be effective. Deep learning is not an intended use case of sk-dist, as it violates (1) and (2) above. Alternatively, at Ibotta <a href="https://medium.com/building-ibotta/heating-up-word2vec-blazingtext-for-real-time-search-c2121bd1396">we’ve been using</a> <a href="https://aws.amazon.com/sagemaker/">Amazon SageMaker</a> for these techniques, which we’ve found to be a more efficient use of compute than Spark for these workloads.</p><h4>Getting Started</h4><p>To get started with sk-dist, check out the <a href="https://github.com/Ibotta/sk-dist#installation">installation guide</a>. The code repository also contains a library of <a href="https://github.com/Ibotta/sk-dist/tree/master/examples">examples</a> to illustrate some of the use cases of sk-dist. <a href="https://github.com/Ibotta/sk-dist/blob/master/CODE_OF_CONDUCT.md">All are welcome</a> to submit issues and contribute to the project.</p><p>If these kinds of projects and challenges sound interesting to you, Ibotta is hiring! Check out our <a href="https://ibotta.com/careers">jobs page</a> for more information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bec530fc1f45" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-ibotta/train-sklearn-100x-faster-bec530fc1f45">Train sklearn 100x faster</a> was originally published in <a href="https://medium.com/building-ibotta">Building Ibotta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Powering a search engine with Amazon SageMaker]]></title>
            <link>https://medium.com/building-ibotta/powering-a-search-engine-with-amazon-sagemaker-43d91adad7be?source=rss-2fc9b61cf1b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/43d91adad7be</guid>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ibotta]]></category>
            <dc:creator><![CDATA[Evan Harris]]></dc:creator>
            <pubDate>Thu, 06 Jun 2019 15:57:04 GMT</pubDate>
            <atom:updated>2019-06-06T15:57:04.374Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Originally published as a </em><a href="https://aws.amazon.com/blogs/machine-learning/powering-a-search-engine-with-amazon-sagemaker/"><em>guest post</em></a><em> on the </em><a href="https://aws.amazon.com/blogs/machine-learning/"><em>AWS Machine Learning Blog</em></a></p><p>The technical divisions within high-growth, mid-stage companies are prone to a unique set of challenges. High on the list for many such companies is building quality applications quickly and effectively.</p><p>On the machine learning (ML) team at <a href="https://ibotta.com/">Ibotta</a> — a mobile app that offers cash back on everyday purchases for millions of users — we have done a good deal of thinking and experimentation on this topic. I would like to share how we leverage AWS to achieve core functionality, such as search with <a href="https://aws.amazon.com/sagemaker/">Amazon SageMaker</a>.</p><p>In this post, I discuss the architecture of Ibotta’s search engine and how we use Amazon SageMaker with other AWS services to integrate real-time ML into the search experience of our mobile application. I hope that this post can shorten your search for a feasible solution to the comparable challenges in your organization, no matter the organization size.</p><p>Creating a streamlined mobile app experience, complete with a comprehensive and user-friendly search flow, is crucial for our business. Customers searching for deals before shopping must find useful content quickly or they’re liable to give up.</p><p>With a dedicated team of search relevancy engineers, ML engineers, designers, and mobile developers, we use as much modern technology as possible to rapidly develop and test new, creative improvements to our search relevancy. We prioritize the use of ML to inject data-driven intelligence into our search engine, pushing us beyond traditional information retrieval techniques.</p><h3>Foundational search infrastructure</h3><p>Our core infrastructure for search at Ibotta rests on our app’s array of <a href="https://pages.awscloud.com/NAMER-field-GC-Micro-Guide-ps-2019-learn.html?trk=paid_srch_%20MSGuide_us_mttc_gated_EXACT_Shared-EXACT&amp;sc_channel=PS&amp;sc_campaign=FIELD-P%7CPS-GO%7CNon-Brand%7CDesktop%7CLD%7Ce-Book%7CModern%20Application%20Development%7CUS%7CEN%7CText%7CNA%7CQ12019&amp;sc_publisher=Google&amp;sc_category=e-Book&amp;sc_country=US&amp;sc_geo=NAMER&amp;sc_outcome=ln&amp;sc_detail=microservices&amp;sc_content=Shared-EXACT&amp;sc_matchtype=e&amp;sc_segment=337061605838&amp;sc_medium=FIELD-P%7CPS-GO%7CNon-Brand%7CDesktop%7CLD%7Ce-Book%7CModern%20Application%20Development%7CUS%7CEN%7CText%7CNA%7CQ12019&amp;s_kwcid=AL!4422!3!337061605838!e!!g!!microservices&amp;ef_id=EAIaIQobChMI4uXowMjc4QIVjrrACh0NNg28EAAYAiAAEgINBfD_BwE:G:s">microservices</a>. Indexed documents live in <a href="https://aws.amazon.com/elasticsearch-service/">Amazon Elasticsearch Service</a>, which contains all of the content available to the mobile client at a given point in time. An internal content service talks to this document store on request and provides additional rules-based filtering functionality to ensure that only content available to the user making the request is returned.</p><p>The content service can receive input search queries and respond with relevant content, taking other contextual considerations into account. The service uses textbook <a href="http://lucene.apache.org/">lucene</a>-style search relevancy techniques to retrieve appropriate content in the Elasticsearch document store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*9f9Hf92U5IkDA4nZ.gif" /></figure><h3>ML-enhanced search infrastructure</h3><p>The foundational search infrastructure leaves substantial room for improvement. Ibotta’s search problem space has unique challenges, particularly revolving content. One week, there might be an offer for certain brands in the app and another week they are gone. This is driven by the retailers with whom we partner, as they often want to promote an item only for a limited time.</p><p>Additionally, some brands and product categories are not available in the app at all, as we have yet to work with those retailers. We still want to show related content to users when their search queries don’t match exact content in the app. For example, a search for a non-carried brand of coffee should return other coffee brands that match across important attributes (flavor, size, price, etc.).</p><p>The solution here is <a href="https://queryunderstanding.com/query-expansion-2d68d47cf9c8">query expansion</a>. This is a common search technique that takes the user’s search query and adds context to it before querying the data store. In one case, we can add value by categorizing the search query in real time, enhancing the content retrieval and sorting algorithm. In other cases, after categorization, we’d like to look up and sort online retailers that specialize in the predicted category and return those as suggestions to the user.</p><p>To make these category inferences on-demand in real time, we use Amazon SageMaker. We can easily train models and deploy them as fully managed <a href="https://en.wikipedia.org/wiki/Representational_state_transfer">REST APIs</a> to which internal microservices can make requests. An example request and response looks something like the following code:</p><pre>Request</pre><pre>{<br>    &quot;term&quot;: &quot;organic prepared horseradish&quot;<br>}</pre><pre>Response</pre><pre>{<br>    &quot;categories&quot;: [<br>        &quot;Condiments, Sauces &amp; Seasonings&quot;,    <br>        &quot;Sauces&quot;<br>    ],<br>    &quot;score&quot;: 0.901242<br>}</pre><p>We use <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/blazingtext.html">BlazingText</a>, an algorithm built in to Amazon SageMaker. The supervised version of BlazingText is a powerful, flexible, and easy to use text classification model. Out of the box, we get scalable distributed training, <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-how-it-works.html">Bayesian hyperparameter optimization</a>, and <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/inference-pipeline-real-time.html">real-time inference endpoint deployment</a>. We’ve spent substantial time training and deploying our own text classification models for other use cases. We found a lot to like using the built-in Amazon SageMaker model and managed training and deployment service.</p><p>In one view, below is the architecture of our ML-enhanced search services architecture. As you’ll see, the querying and retrieval mechanism described above (and captured here as well) is complemented by SageMaker, which provides two distinct value-adds. First, it enables us to categorize the search query to deliver more relevant results, and second, it enables us to provide online retailers whose offerings are relevant to the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*BmgFvN0s2jD6wEEa.gif" /></figure><p>An additional ML value-add is our UPC barcode scan feature. Users can scan barcodes of consumer products with our app. If purchasing that UPC satisfies an offer, we return exact matches. If there isn’t an exact match, we use an unsupervised text similarity algorithm to find related offers to suggest to the user. If they can get cash back with our app, perhaps they will consider an alternative to the product that they scanned.</p><p>With the UPC feature, we know upfront the universe of UPCs for which we potentially have a similarity suggestion. Predictions can be made offline and written to an online data store, from which our services can make low-latency requests in real time. We use a combination of <a href="https://aws.amazon.com/s3/">Amazon S3</a>, <a href="https://aws.amazon.com/lambda/">AWS Lambda</a>, <a href="https://airflow.apache.org/">Apache Airflow</a>, and <a href="https://aws.amazon.com/dynamodb/">Amazon DynamoDB</a> for this process. We see that addition to our architecture in the following diagram, in which the UPC input becomes a search query against which we execute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*aRGj5YbLzn0BDupx.gif" /></figure><p>We then get a mix of on-demand and batch ML models used as needed to enhance our search experience. With a broad services toolset, we are able to select the right tool for the job. Our production environment consists of fully managed AWS services, including offline data storage, online data storage, data transfer, and ML services.</p><h3>Building to scale</h3><p>When technologists talk about building to scale, they are often referring to horizontal scalability — perhaps something like <a href="https://aws.amazon.com/s3/">Amazon S3</a> for storage or managed <a href="https://kubernetes.io/">Kubernetes</a> for compute. With these services, horizontal scaling is effectively infinite.</p><p>However, it’s often also useful to talk about scalability in terms of our ability to add new functionality to our services without overcomplicating any individual service or code base. Using microservices built on top of AWS, we are able to add or upgrade features while imposing minimal risk to the existing ecosystem.</p><p>We are also able to compartmentalize ownership, particularly allowing ML engineers to own their own services end-to-end. As long as the API contract doesn’t change, the ML team can iterate on their models independent of any contact with the owners of dependent services. Amazon SageMaker enables developers with basic Python skills and ML knowledge to support production microservices that integrate directly into our stack.</p><p>This sets us up for future iterations of our search service architecture that don’t require substantial cross functional efforts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*AYRq_nIbFHGLcXr4.gif" /></figure><p>In this setup, perhaps we migrate our UPC prediction pipeline to an Amazon SageMaker service capable of more advanced feature extraction and inference from UPCs to predict related content. We can also migrate our Elasticsearch document store to sit directly behind the search service for more specialized search-oriented document indexing. Then we solely rely on the content service for rules-based user level filtering.</p><p>Finally, an exciting ML use case is <a href="https://en.wikipedia.org/wiki/Learning_to_rank">learning to rank</a>. After the search service retrieves a candidate set of content, we can use an Amazon SageMaker service to dynamically re-rank content in real time. This can factor in known features about content, personalization, as well as trends and seasonality.</p><p>Thanks to AWS, we have architecture that sets us up for success. We compartmentalize project work with simple integration points and ownership is clear and straightforward. ML teams can build simple services that integrate directly with our backend platform, all on top of managed infrastructure.</p><h3>Conclusion</h3><p>We study how the tech giants like <a href="https://medium.com/airbnb-engineering/machine-learning-powered-search-ranking-of-airbnb-experiences-110b4b1a0789">Airbnb</a>, <a href="https://www.youtube.com/watch?v=4Yag3SrAMnI">Etsy</a>, <a href="https://www.youtube.com/watch?v=6G-xo628CHU">Linkedin</a>, <a href="https://tech.wayfair.com/2018/10/how-we-use-machine-learning-and-natural-language-processing-to-empower-search/">Wayfair</a>, and <a href="https://medium.com/the-graph/search-serving-and-ranking-at-pinterest-224707599c92">Pinterest</a> operate their search engines and strive to do the same at Ibotta. We regularly think about how our engineering team is comparatively fractional in size. Yet we are well-equipped to deliver similar experiences with the setup we have: our own microservices on top of AWS. The AWS services that we rely on enable us to do rapid iteration and testing that would otherwise be out of reach or impossibly slow to implement. With AWS as our preferred AI/ML provider and the underpinning of our tech stack, we’re excited about what’s next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43d91adad7be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-ibotta/powering-a-search-engine-with-amazon-sagemaker-43d91adad7be">Powering a search engine with Amazon SageMaker</a> was originally published in <a href="https://medium.com/building-ibotta">Building Ibotta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heating up word2vec: BlazingText for Real-time Search]]></title>
            <link>https://medium.com/building-ibotta/heating-up-word2vec-blazingtext-for-real-time-search-c2121bd1396?source=rss-2fc9b61cf1b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2121bd1396</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Evan Harris]]></dc:creator>
            <pubDate>Mon, 04 Feb 2019 15:01:01 GMT</pubDate>
            <atom:updated>2019-09-03T17:16:01.251Z</atom:updated>
            <content:encoded><![CDATA[<p>On the machine learning team at <a href="https://ibotta.com/">Ibotta</a> we try to strike the right balance between utilizing cutting edge technology and chasing shiny objects. There is always a new framework or package being released that offers a new way to solve a familiar set of problems. Many of these can be distractions, but occasionally something comes along that really does check all of the boxes. For us, a recent example of that is running BlazingText on Amazon SageMaker for <a href="https://en.wikipedia.org/wiki/Document_classification">text document classification</a>.</p><p>The following outlines our implementation, and how we utilized BlazingText to add value to a critical feature of Ibotta’s mobile app.</p><h3>Searching for Relevancy</h3><p><a href="https://opensourceconnections.com/blog/2014/06/10/what-is-search-relevancy/">Search relevancy</a> is a really interesting problem. We hadn’t spent much time thinking about it on the machine learning team until recently. Since then it has piqued our interest not only about applications and algorithms for machine learning in search relevancy, but infrastructure for efficient deployment and maintenance of solutions we might come up with.</p><p>Here is one basic problem our search relevancy effort has faced. Classic techniques for search work great when users search with keywords and phrases that match the language used to name and describe content in our app. For instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*sXg5NMcbX4cT0vut3fJ4Gg.png" /><figcaption>Search results for “bread”</figcaption></figure><p>A search for “bread” is straightforward. We have highly relevant content that matches this search query using a <a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/relevance-intro.html">simple text matching algorithm</a>. We use <a href="https://aws.amazon.com/elasticsearch-service/">Amazon Elasticsearch</a> and its out-of-the-box features for this. But often users might search for words or phrases that are closely related to content we have in the app, but the language used doesn’t match any of the descriptive text we have associated to content in our searchable data store. For instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*ZIdo-WBd5Ns2V_G2GKY3xw.png" /><figcaption>Search results for “zinfandel”</figcaption></figure><p>Here is a search for “zinfandel” where the user is looking for a specific grape, but the wine offers in the app are typically for any variety of wine sold by the appropriate label. Our search engine knows that “zinfandel” is wine and is therefore able to return offers for any variety of wine. This experience is <em>so much better</em> than a dead end (“Sorry, no results”) for the user. The user can consider any of the wine labels we carry offers for and either buy an appropriate bottle of zinfandel or choose something related like another grape variety. This drives satisfaction for our users as well as more engagement for the content in our app.</p><p>So how do we make this happen? There are a few things to keep in mind about the problem space. First of all our inventory revolves rapidly, so indexing this data (loading it into our searchable content store) needs to happen continuously. Additionally, we want the indexing process to be as automated as possible. And finally, we don’t want to index <em>a ton</em> of data along with each piece of content in our searchable data store. Here are some potential solutions:</p><ol><li><em>For every search keyword we can think of, hard code content that should be returned given a search containing that keyword</em></li><li><em>For every piece of searchable content, hard code search keywords that we might expect users to search for that should return that content</em></li><li><em>Utilize a </em><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-synonym-tokenfilter.html"><em>synonyms file</em></a><em> with hardcoded mappings of keywords used to associate potential user search keywords with content</em></li><li><em>Categorize content at setup time, categorize search queries at query time, and match search query category predictions to content category predictions</em></li></ol><p>It’s probably not surprising that (4) is what we implemented. Options (1) and (2) violate our requirements. These are too top heavy and manual at content setup time, and would additionally involve heavy weight data structures to be indexed alongside our content in our searchable content store. Option (3) is a bit too rigid and deterministic when it comes to multi-term or multi-phrase search queries. Continuous ingestion of a large synonyms file would be an additional challenge as our searchable content store is continuously updating.</p><p>Option (4) has additional advantages in that a categorization model can learn which keywords in a search query to focus on in its effort to categorize (effectively ignoring contextually inconsequential tokens), where a text matching solution would need some top down technique to sort relevant content based on the various terms and phrases that could be contained in a search query. While the examples “bread” and “zinfandel” are simple, users can type anything they want into the search bar. We need to infer their categorical intent regardless of whether or not their query is something simple that we’ve seen before.</p><p>So bringing the conversation back to machine learning, this is where we land. We have a fairly straightforward task: categorize search queries in real-time.</p><h3>BlazingText</h3><p>So what kind of model or framework do we use? In 2019, the sky’s the limit for open source options for doing something like this. We have some <a href="https://towardsdatascience.com/multi-class-text-classification-with-scikit-learn-12f1e60e0a9f">tried and true techniques</a> for solving this kind of problem, but we’d been eager to try out some of Amazon SageMaker’s functionality since we work mostly with AWS infrastructure and had been curious.</p><p><a href="https://aws.amazon.com/sagemaker/">SageMaker</a> is AWS’ framework agnostic model training and deployment service. In their own words, “Amazon SageMaker provides every developer and data scientist with the ability to build, train, and deploy machine learning models quickly.” It was launched late in 2017 and we began experimenting a few months later. This lead us to <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/blazingtext.html">BlazingText</a>.</p><p>Cutting to the chase here, BlazingText is very cool. If you’ve spent some time working with <a href="https://en.wikipedia.org/wiki/Word2vec">word2vec</a>, <a href="https://medium.com/scaleabout/a-gentle-introduction-to-doc2vec-db3e8c0cce5e">doc2vec</a>, <a href="https://fasttext.cc/">fastText</a>, or others and you work in an AWS friendly environment, check it out. This suite of models learn vector representations of words based on their linguistic context in the training data. These word vector representations can be used for pre-processing in a supervised text document classifier.</p><p>AWS first released <a href="https://aws.amazon.com/blogs/machine-learning/amazon-sagemaker-blazingtext-parallelizing-word2vec-on-multiple-cpus-or-gpus/">BlazingText</a> in early 2018. It basically scales <a href="https://research.fb.com/fasttext/">Facebook’s fastText</a> on specialized distributed infrastructure, provisioned on-demand. Since its first release, AWS released <a href="https://aws.amazon.com/blogs/machine-learning/enhanced-text-classification-and-word-vectors-using-amazon-sagemaker-blazingtext/">additional features to BlazingText</a> in July of 2018 which really set it up to become an ideal candidate for our search relevancy use case:</p><ol><li><strong>Supervised mode</strong> — an additional multi-class or multi-label classifier step after the embeddings vectors are generated, turning BlazingText into a generalized text classification algorithm, boasting 100x training performance improvements over deep learning alternatives achieving similar accuracy</li><li><strong>Real-time predictor</strong> — support for SageMaker’s real-time predictor API functionality which hosts a trained BlazingText model as a fully managed, auto-scaling, monitored service as a REST API endpoint for low latency, high throughput prediction as a service</li></ol><p>Here is the basic architecture for supervised mode from SageMaker’s docs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/0*6aVWfzUYiKw2Um7w" /><figcaption>Supervised Mode for BlazingText</figcaption></figure><p>This enabled Ibotta’s machine learning team to train a large scale multi-class classifier leveraging swaths of training data from internal product dictionaries and historical search data to produce a real-time machine learning API. This model leverages word embeddings learned from the semantic relationships between words in our product descriptions, as well as our internal categorization hierarchy used to categorize content in the app.</p><p>It <em>really</em> wasn’t that hard. With BlazingText, the exercise simply becomes properly obtaining, cleaning and aggregating training data. We’ve spent a lot of time building classifiers to categorize text documents at Ibotta using various frameworks and infrastructure. This was one of the easier, cheaper and more performant techniques we’ve found to train a multi-class model with a high number of classes with a large amount of training data.</p><p>Not to mention the <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-how-it-works.html">bayesian hyperparameter optimization</a> that comes out of the box with SageMaker. We use this to parameterize the BlazingText model, particularly looking for the optimal word embedding dimension size. SageMaker spins up necessary resources on-demand to train and score various hyperparameter sets in parallel. While our models were looking good with sane defaults, this off-of-the-shelf routine for optimizing hyperparameters ensures we found the best model for our solution.</p><p>We get to leverage as much of our data as we want to, and quickly train and optimize a high quality model that meets our needs. This is all with just a couple of API calls pointing to our training data stored in S3.</p><h3>Custom Machine Learning APIs</h3><p>For a very applied team that spends a lot of time on integrating models and predictions into our larger engineering infrastructure, simple integration points are really exciting to us. As it turns out, <em>one way to integrate machine learning with microservices inside of a microservices infrastructure is </em><strong><em>with another microservice</em></strong>.</p><p>Using SageMaker we were able to create a REST endpoint available for use by any other microservice in our infrastructure. Setting up an endpoint to serve predictions is one simple API call to SageMaker after model training and validation (you can also do this in the console with all clicks and no code).</p><p>If you’ve spent a lot of time with large scale batch predictions where your end product is to ship data (as we have), it’s really fun to do something different and ship a machine learning prediction API. Especially with a consumer facing app, you get people pressing buttons on their smartphones all over the country triggering calls to your service. They are then seeing results as a function of the prediction your model makes at that instant.</p><p>You can watch it in real-time as well. SageMaker provides monitoring through cloud watch in the AWS console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_iy09IVDlek-mEhM" /><figcaption>Prediction Latency for Inference Pipeline</figcaption></figure><p>Just one example of some of the monitoring charts you can build, this is average latency of the BlazingText endpoint over the last hour as of time of this writing. This includes the BlazingText prediction, as well as custom pre and post processing steps (written in python, using <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/inference-pipelines.html">inference pipelines</a>) we tack on for a more custom experience. These inference pipelines allow us to build in text pre-processing like lowercasing, special character removal, and stemming at prediction time. Additionally, we apply post-processing which consists of probability score thresholding and parent category lookup from an in-memory dictionary.</p><p>It’s also a fully managed service so we don’t need to worry much about uptime and resiliency, though we do build in failure modes for the services calling SageMaker in case it does go down.</p><h3>Conclusion</h3><p>The machine learning world abounds with new tools, models and frameworks. While a year is a long time, much of SageMaker feels very new, which comes with its own challenges for getting up to speed (there isn’t much on <a href="https://stackoverflow.com/questions/tagged/amazon-sagemaker">stack overflow</a>). Starting out on day one, it’s definitely easier to train a regression your laptop than it is to train a BlazingText model on SageMaker. But ultimately the scalability and access to cutting edge models are worth it.</p><p>On the machine learning team at <a href="https://ibotta.com/">Ibotta</a> we use what we can stand up and integrate quickly, we use what is fun to build, and we use what works. At the end of the day, using state-of-the-art machine learning frameworks to power the search experience for millions of users on their smartphones is a pretty fun thing to be a part of.</p><p>If these kinds of projects and challenges sound interesting to you, Ibotta is hiring! Check out our <a href="https://ibotta.com/careers">jobs page</a> for more information. Take a look at some of our other work on the machine learning team <a href="https://medium.com/building-ibotta/train-sklearn-100x-faster-bec530fc1f45">here</a>, <a href="https://medium.com/building-ibotta/ibottas-recommender-system-7a4034773bf9">here</a> and <a href="https://medium.com/building-ibotta/erupt-expected-response-under-proposed-treatments-ff7dd45c84b4">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2121bd1396" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-ibotta/heating-up-word2vec-blazingtext-for-real-time-search-c2121bd1396">Heating up word2vec: BlazingText for Real-time Search</a> was originally published in <a href="https://medium.com/building-ibotta">Building Ibotta</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>