<?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 Benjamin Wang on Medium]]></title>
        <description><![CDATA[Stories by Benjamin Wang on Medium]]></description>
        <link>https://medium.com/@benjamin-wang?source=rss-9f912e7eae81------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xyPZWvFJ13udAx-P6KSVjw.jpeg</url>
            <title>Stories by Benjamin Wang on Medium</title>
            <link>https://medium.com/@benjamin-wang?source=rss-9f912e7eae81------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 17:44:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benjamin-wang/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[ML Pipelines with Grid Search in Scikit-Learn]]></title>
            <link>https://medium.com/data-science/ml-pipelines-with-grid-search-in-scikit-learn-2539d6b53cfb?source=rss-9f912e7eae81------2</link>
            <guid isPermaLink="false">https://medium.com/p/2539d6b53cfb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <dc:creator><![CDATA[Benjamin Wang]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 16:34:13 GMT</pubDate>
            <atom:updated>2021-05-15T10:08:15.546Z</atom:updated>
            <content:encoded><![CDATA[<h3>ML Pipeline with Grid Search in Scikit-Learn</h3><h4>ML Pipeline is an important feature provided by Scikit-Learn and Spark MLlib. It unifies data preprocessing, feature engineering and ML model under the same framework. This abstraction drastically improves maintainability of any ML project, and should be considered if you are serious about putting your model in production.</h4><p>Let’s start by outlining some main benefits of using ML pipeline, already.</p><ul><li><strong>Unified API for both data transformations and modelling</strong></li><li><strong>No extra preprocessing steps needed during model serving time</strong></li><li><strong>Joint grid search possible including data preprocessing steps/parameters and model selection/parameters</strong></li><li><strong>Compatible with big data framework such as Spark</strong></li></ul><p>The last point might not be immediately obvious for some. Imagine if one day your model needs to train on large amount of data. You might have no better choice but to use some distributed framework like Spark. Using ML pipeline will make migrating to Spark a breeze to work with. One reason is that Spark MLlib has a similar ML pipeline feature. Another more fundamental reason is <strong>functional programming.</strong></p><p>ML pipeline draws many similarities with<strong> functional programming </strong>(which Spark also follows), in that it treats transformations and estimators(models) as operators on data. Data maintains <strong>immutability (a core idea of FP)</strong>, as they just pass through different components of the pipeline, get transformed into new format during the process. At the end of the pipeline, we get some prediction results out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*hIA3XGdALAjKjM1A2vYnAA.png" /><figcaption>Example pipeline (image by author, generated with scikit-learn)</figcaption></figure><p>In the example pipeline, we have a preprocessor step, which is of type ColumnTransformer, containing two sub-pipelines:</p><ul><li>num_transform is a sub-pipeline intended for numeric columns, which fills null values and convert the column to a standard distribution</li><li>cat_transform is a another sub-pipeline intended for categorical columns, which does one-hot encoding</li></ul><p>Following the preprocessor transformer, we have an estimator , a default logistic regressor in this case.</p><p>With this pipeline, one can combine data preprocessing together with modelling, and even include more complex feature engineering by creating custom transformers.</p><p>To create your own transformer, you need to create a class which inherits from both sklearn.base.BaseEstimator and sklearn.base.TransformerMixin and implement fit and transform methods.</p><h3>How to create a pipeline?</h3><p>Let’s go through a running example (<a href="https://github.com/wlongxiang/mlpipeline/blob/main/ml_pipeline_with_grid_search.ipynb">the complete code is available on Github</a>) with the Titanic dataset containing features of passengers and labels indicating if one has survived.</p><p>We want to build a classifier to predict if a given passenger will survive.</p><pre>from sklearn.datasets import fetch_openml<br>import numpy as np</pre><pre>np.random.seed(0)</pre><pre># Load data from <a href="https://www.openml.org/d/40945">https://www.openml.org/d/40945</a><br>X, y = fetch_openml(&quot;titanic&quot;, version=1, as_frame=True, return_X_y=True)</pre><p>We will consider the following 4 features, of which age and fare are numeric and sex and pclass are categorical (note: one can also treat pclass as numeric, but that’s not relevant for discussion here).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*3DT3ZwdtIT280p3STrDcRg.png" /></figure><p>Now, let’s build the pipeline to do some data preprocessing as indicated previously.</p><pre>numeric_features = [&quot;age&quot;, &quot;fare&quot;]<br>numeric_transformer = Pipeline(steps=[<br>    (&quot;imputer&quot;, SimpleImputer(strategy=&quot;mean&quot;)),<br>    (&quot;scaler&quot;, StandardScaler())<br>])</pre><pre>categorical_features = [&quot;sex&quot;, &quot;pclass&quot;]<br>categorical_transformer = OneHotEncoder(handle_unknown=&quot;ignore&quot;)</pre><pre>preprocessor = ColumnTransformer(transformers=[<br>    (&quot;num_transform&quot;, numeric_transformer, numeric_features),<br>    (&quot;cat_transform&quot;, categorical_transformer, categorical_features)<br>])</pre><pre>pipeline = Pipeline(steps=[(&quot;preprocesser&quot;, preprocessor), (&quot;classifier&quot;, LogisticRegression())])<br>pipeline</pre><p>Alternatively, there is a slightly more compact API make_pipeline and make_column_transformer where we don’t need to pass names of each step explicitly. <strong>However, the following section will be based on the previous verbose version, because we like to name things as we like :).</strong></p><pre>from sklearn.compose import make_column_transformer<br>from sklearn.pipeline import make_pipeline</pre><pre>numeric_transformer = make_pipeline(<br>    SimpleImputer(strategy=&#39;mean&#39;),<br>    StandardScaler())</pre><pre>categorical_transformer = make_pipeline(OneHotEncoder(handle_unknown=&#39;ignore&#39;))</pre><pre>preprocessor = make_column_transformer(<br>    (numeric_transformer, numeric_features),<br>    (categorical_transformer, categorical_features))</pre><pre>pipeline = make_pipeline(preprocessor, LogisticRegression())<br>pipeline</pre><p>One handy tip, one can visualize the pipeline in Jupyter notebook by including the code below. It creates a nice diagram as shown before.</p><pre>from sklearn import set_config<br>set_config(display=&#39;diagram&#39;)<br>pipeline</pre><h3>How to train a model?</h3><p>Training a model is no different than a pure estimator. You just call fit. Below we first do a a standard train test data split to test model performance. Then, you just call pipeline.fit() on your training data, that’s it.</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)<br>pipeline.fit(X_train, y_train)<br>score = pipeline.score(X_test, y_test)<br>print(score)<br>0.7977099236641222</pre><p>What really happens under the hood is that the training data pass through the steps defined in the pipeline (including the classifier estimator) as if it is one model.</p><h3>How to save and load a model?</h3><p>At this point, one might wonder can I also save my pipelined model as I used to do with a standalone model? The answer is a definite yes.</p><p>And there is a bonus point of putting the data processing and modelling together in one saved model. <strong>Now you don’t need to think about what preprocessing steps to take during prediction time, they are already an integral part of the model</strong>. This prevents strange prediction results from happening in production.</p><pre>import joblib<br>joblib.dump(pipeline, &#39;your_pipeline.pkl&#39;)</pre><pre>joblib.load(&#39;your_pipeline.pkl&#39;).score(X_test, y_test)<br>0.7977099236641222</pre><p>We use joblib to save and load the pipeline, and it produces the same score, which verifies the correctness, and indeed we see no preprocessing is needed, as promised.</p><h3>How to do grid search on a pipeline?</h3><p>ML pipeline enables us not only to search parameters for the estimator, but also parameters for all the preprocessing steps. In other words, we can now tune ML models, and preprocessing options all together.</p><p>For argument sake, say, we are not sure if filling null values by mean ormedian strategy is a better option, and we are also not sure about how much regularization is needed for the LogisticRegressor . Therefore, we want to find out which is the best missing value filling strategy and the best regularization weight at the same time. To achieve that, we can construct the paramter grid as follows:</p><pre>param_grid = [<br>    {<br>        &quot;preprocesser__num_transform__imputer__strategy&quot;: [&quot;mean&quot;, &quot;median&quot;],<br>        &quot;classifier__C&quot;: [0.1, 1.0, 10.0, 100.0],<br>        &quot;classifier&quot;: [LogisticRegression()]<br>    }<br>]</pre><p>Note: <strong>sklearn uses double underscore as separator</strong>. classifier key is the same as the pipeline name for estimator in the pipeline definition, classifier__C basically tells the grid searcher that we would like to try these provided values for C which is a parameter for the classifier LogisticRegressor to define regularization weight.</p><p>As you might notice, you can also concat the double underscore syntax. preprocesser__num_transform__imputer_strategy defines different values to try out for the imputer step’s strategy parameter.</p><p>Finally, we can start the grid search, since we have 2 values for strategy and 4 values for C , in total there are 2*4=8 candidates to in the search space.</p><pre>grid_search = GridSearchCV(model, param_grid, cv=10, verbose=1,n_jobs=-1)<br>grid_search.fit(X_train, y_train)</pre><p>The output is shown below, since we have a 10 fold cross validation for each combination, in total we need to fit 80 models! One can see how easily grid search can explode.</p><pre>Fitting 10 folds for each of 8 candidates, totalling 80 fits</pre><pre>[Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers.<br>[Parallel(n_jobs=-1)]: Done  80 out of  80 | elapsed:    4.5s finished</pre><p>What if we want to try out different classifiers? We can construct more complex parameter grid to achieve this.</p><pre>param_grid = [<br>    {<br>        &quot;preprocesser__num_transform__imputer__strategy&quot;: [&quot;mean&quot;, &quot;median&quot;],<br>        &quot;classifier__C&quot;: [0.1, 1.0, 10.0, 100.0],<br>        &quot;classifier&quot;: [LogisticRegression()]<br>    },<br>    {<br>        &quot;preprocesser__num_transform__imputer__strategy&quot;: [&quot;mean&quot;, &quot;median&quot;],<br>        &quot;classifier__n_estimators&quot;: [10, 100, 1000],<br>        &quot;classifier&quot;: [RandomForestClassifier()]<br>    }<br>]<br>grid_search = GridSearchCV(model, param_grid, cv=10, verbose=1,n_jobs=-1)<br>grid_search.fit(X_train, y_train)</pre><p>In the code above, we use two dictionaries in the parameter grid to add an extra set of search options, which uses a random forest classifier instead of a logistic regressor.</p><p>One might ask, what is the number of combinations now? Since each dictionary defines a different set, <strong>we should add up across dictionaries, multiply within dictionaries</strong>. That gives us 2*4*1 + 2*3*1 = 14 candidates.</p><p>This is verified in the output:</p><pre>Fitting 10 folds for each of 14 candidates, totalling 140 fits</pre><pre>[Parallel(n_jobs=-1)]: Using backend LokyBackend with 4 concurrent workers.<br>[Parallel(n_jobs=-1)]: Done  76 tasks      | elapsed:    1.5s<br>[Parallel(n_jobs=-1)]: Done 140 out of 140 | elapsed:   26.6s finished</pre><h3>Summary</h3><p>We have discussed the main benefits of using ML pipeline with a running example.</p><p>We have also seen how convenient the pipeline concept can be, and powerful at the same time. The latter point becomes evident after we see how easy it is to do a joint grid search.</p><p>Last but not least, it should not be a surprise to see that Spark MLlib has almost identical features as ML pipeline in scikit-learn , interested readers can checkout: <a href="https://spark.apache.org/docs/latest/ml-pipeline.html">https://spark.apache.org/docs/latest/ml-pipeline.html</a>, or I might write another blog on that.</p><h3>Notes</h3><ol><li>Code available on GitHub: <a href="https://github.com/wlongxiang/mlpipeline/blob/main/ml_pipeline_with_grid_search.ipynb">https://github.com/wlongxiang/mlpipeline/blob/main/ml_pipeline_with_grid_search.ipynb</a></li><li>Some materials to read for making your own transformers: <a href="https://sklearn-template.readthedocs.io/en/latest/user_guide.html">https://sklearn-template.readthedocs.io/en/latest/user_guide.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2539d6b53cfb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ml-pipelines-with-grid-search-in-scikit-learn-2539d6b53cfb">ML Pipelines with Grid Search in Scikit-Learn</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Locality Sensitive Hashing]]></title>
            <link>https://benjamin-wang.medium.com/locality-sensitive-hashing-6b859d164ab1?source=rss-9f912e7eae81------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b859d164ab1</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[lsh]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Benjamin Wang]]></dc:creator>
            <pubDate>Mon, 25 Jan 2021 16:00:29 GMT</pubDate>
            <atom:updated>2021-05-18T14:08:21.801Z</atom:updated>
            <content:encoded><![CDATA[<h3>Locality Sensitive Hashing: An Short Intro Based on Minhash</h3><p>Hashing maps objects into different bins. Unlike conventional hashing functions which minimize collision probability, locality sensitive hashing functions maximize it for similar objects. In other words, for a given distance measure, similar items are more likely to be mapped to the same bin with LSH. This way, we can find neighbors for a certain item in a smaller area of neighborhood (hence the name “locality sensitive” hashing), without comparing it against all items. This dramatically speeds up nearest neighbor search.</p><p>Here we use “objects” in a broad sense to represent any data (e.g., sets, arrays, documents, etc.). One example is a text document represented by a bag of words, another example is a shopping basket containing a set of grocery items.</p><p>There are different LSH functions associated with different distance measures. LSH functions are used to group similar items into the same buckets. Before we can do that, we first need to define “similar” in terms of the distance measure under consideration. That’s why LSH functions are always associated with a distance measure.</p><p>Loosely speaking, for a given distance measure, we choose a LSH function such that similar items are more likely to group together after hashing.</p><p><strong>Min hashing functions for Jaccard distance</strong></p><p>The min hashing functions convert a set into a signature. The length of the signature is equal to the number of permutations on the rows.</p><blockquote>The probability that the minhash function for a random permutation of rows produce the same value for two sets are equal to the Jaccard similarity of those two sets.</blockquote><p>Another way to interpret this is that: the minhashing output is actually a <strong>probability estimation</strong> that two sets are identical.</p><p>With the signatures of two sets, we can simply calculate the fraction of elements which are equal at the same location, this fraction serves as a good approximation to the Jaccard Similarity of the two sets.</p><p>Using the datasketch package:</p><pre><strong>from</strong> <strong>datasketch</strong> <strong>import</strong> MinHash<br><br>data1 = [&#39;minhash&#39;, &#39;is&#39;, &#39;a&#39;, &#39;probabilistic&#39;, &#39;data&#39;, &#39;structure&#39;, &#39;for&#39;,<br>        &#39;estimating&#39;, &#39;the&#39;, &#39;similarity&#39;, &#39;between&#39;, &#39;datasets&#39;]<br>data2 = [&#39;minhash&#39;, &#39;is&#39;, &#39;a&#39;, &#39;probability&#39;, &#39;data&#39;, &#39;structure&#39;, &#39;for&#39;,<br>        &#39;estimating&#39;, &#39;the&#39;, &#39;similarity&#39;, &#39;between&#39;, &#39;documents&#39;]<br><br>m1, m2 = MinHash(), MinHash()<br><strong>for</strong> d <strong>in</strong> data1:<br>    m1.update(d.encode(&#39;utf8&#39;))<br><strong>for</strong> d <strong>in</strong> data2:<br>    m2.update(d.encode(&#39;utf8&#39;))</pre><pre>print(&quot;Estimated Jaccard for data1 and data2 is&quot;, m1.jaccard(m2))<br># or compute using the digest of minhashing<br>dg1 = m1.digest()<br>dg2 = m2.digest()</pre><pre># the nominator is number of places when both digests are equal<br># the denominator can be for dg1 or dg2, they are same length<br>j = np.sum(dg1==dg2)/len(dg2)<br>print(&quot;another estimated from digest&quot;, j)</pre><pre>s1 = set(data1)<br>s2 = set(data2)<br>actual_jaccard = float(len(s1.intersection(s2)))/float(len(s1.union(s2)))<br>print(&quot;Actual Jaccard for data1 and data2 is&quot;, actual_jaccard)</pre><pre># the similarity is 0.7109375</pre><p>We can verify that the results produced by MinHashing is the same as a rudimentary Jaccard similarity.</p><p>Alternatively, one can also verify the results by accessing the signature by m1.digest():</p><pre>num_of_common = np.argwhere(m1.digest()==m2.digest()).flatten()<br>len(num_of_common)/128 # 128 is the default number of perms<br></pre><p>In summary, we can use the minhashing functions associated with Jaccard distance to group those similar items (similar in terms of the distance metric under consideration, in here it is Jaccard).</p><p><strong>Bit sampling for Hamming distance</strong></p><p>We can use bit sampling as a LSH function accompanying Hamming distance.</p><p>See <em>Mining of massive dataset Section 3.7.</em></p><p>Or this nice post: <a href="https://randorithms.com/2019/09/19/Visual-LSH.html">https://randorithms.com/2019/09/19/Visual-LSH.html</a></p><p><strong>Random projection for cosine distance</strong></p><p>Similar to minhash for Jaccard similarity, we can use random projections to approximate the cosine similarity.</p><p>By randomly choosing hyperplanes defined by a unit vector, we can use monte carlo methods to estimate the similarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*DOEyu7_90IOzT97i.png" /></figure><p>We randomly chose a large number of random planes defined by vector <strong><em>v, </em></strong><em>the probability that the dot products of x *v and y*v has different signs are equal to the angle theta.</em></p><p>As we can see, the closer (similar) two vectors are, the more often a random projection will lead to the same sign of both dot products.</p><p><a href="https://tostr.pl/blog/locality-sensitive-hashing-for-angular-distance-in-python/">This blog</a> provides a good explanation on this.</p><p>One can also see <em>Mining of massive dataset Section 3.7.</em></p><p><strong>LSH functions for Euclidean space</strong></p><p>This topic is a little bit more complicated, see this nice post: <a href="https://randorithms.com/2019/09/19/Visual-LSH.html">https://randorithms.com/2019/09/19/Visual-LSH.html</a></p><h3>Notes</h3><ol><li>A visual and intuitive introduction: <a href="https://randorithms.com/2019/09/19/Visual-LSH.html">https://randorithms.com/2019/09/19/Visual-LSH.html</a></li><li>On random projection for cosine distance: <a href="https://en.wikipedia.org/wiki/Locality-sensitive_hashing#Random_projection">https://en.wikipedia.org/wiki/Locality-sensitive_hashing#Random_projection</a></li><li>LSH in the larger family of Nearest Neighbour Search problem: <a href="https://en.wikipedia.org/wiki/Nearest_neighbor_search">https://en.wikipedia.org/wiki/Nearest_neighbor_search</a></li><li>Two popular Open Source implementations: facebook <a href="https://github.com/facebookresearch/faiss">https://github.com/facebookresearch/faiss</a> and spotify <a href="https://github.com/spotify/annoy">https://github.com/spotify/annoy</a></li><li>A very good blog post on angular/cosine distance LSH: <a href="https://tostr.pl/blog/locality-sensitive-hashing-for-angular-distance-in-python/">https://tostr.pl/blog/locality-sensitive-hashing-for-angular-distance-in-python/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b859d164ab1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bloom filter]]></title>
            <link>https://benjamin-wang.medium.com/bloom-filter-eddcaeb66b31?source=rss-9f912e7eae81------2</link>
            <guid isPermaLink="false">https://medium.com/p/eddcaeb66b31</guid>
            <category><![CDATA[bloom-filter]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Benjamin Wang]]></dc:creator>
            <pubDate>Mon, 25 Jan 2021 13:57:34 GMT</pubDate>
            <atom:updated>2021-05-18T14:06:26.965Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bloom Filter: A Short Introduction</h3><p>Bloom filter is a <strong>probabilistic data structure</strong> designed to tell you if a member is in a set in a highly memory and time efficient manner. In that sense, it is similar to a <strong>set, </strong>but it does it with an adjustable false positive rate. In bloom filter, false positives are possible, but false negatives are not. In other words, when testing if a member is in a set, it either says “possibly in a set” or “definitely not in a a set”. When it says yes, it might be wrong with an often small enough chance, but when it says no, that means no.</p><p>A brilliant example is provided in this <a href="https://llimllib.github.io/bloomfilter-tutorial/">blog post</a>.</p><p>Bloom filter is especially fit for large set, where it is hard to fit the whole set into main memory as it is, and when it is okay to allow certain rate of false positives.</p><p>One typical example is account name selection while creating your gmail account. You might wonder how does google know so fast that if an email account is taken in a blink? Think about it, Gmail has around 1.5 billions users, it is impossible to search through all of them. Nor it is ideal to store all those existing email addresses in main memory.</p><p>Instead, we can use a bit array with some help from a few hash functions to encode existing email addresses. When a user types a desired new address, we just need to check if the hash outputs (indices in the bit array) are all 1’s. If they answer is yes, there is<strong> high probability </strong>this address is already taken, otherwise, this address is <strong>definitely</strong> not taken.</p><p>The false positive rate is approximated by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*7rII0l8GrJtvRmXb-wL2zg.png" /><figcaption>From wikipedia</figcaption></figure><p>where <em>m</em> is number of bits in the bit array, <em>n</em> is the number of elements in the existing set, <em>k</em> is the number of hash functions.</p><p>To minimize the false positive rate given fixed m and n, we can choose the number of hash functions following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*LqToWzcdbWsuUKvvy_uT6g.png" /><figcaption>From wikipedia</figcaption></figure><h3>Notes:</h3><ol><li>For the calculation of False Positive rate: see wikipedia: <a href="https://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives">https://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives</a></li><li>For an interactive example: <a href="https://llimllib.github.io/bloomfilter-tutorial/#footnote2">https://llimllib.github.io/bloomfilter-tutorial</a></li><li>For another easy read on Medium: <a href="https://medium.com/techspace-usict/bloom-filter-a-probabilistic-search-approach-in-data-structures-cb3dd48c6632">https://medium.com/techspace-usict/bloom-filter-a-probabilistic-search-approach-in-data-structures-cb3dd48c6632</a></li><li>A python C extension: <a href="http://axiak.github.io/pybloomfiltermmap/ref.html">http://axiak.github.io/pybloomfiltermmap/ref.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eddcaeb66b31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ranking Evaluation Metrics for Recommender Systems]]></title>
            <link>https://medium.com/data-science/ranking-evaluation-metrics-for-recommender-systems-263d0a66ef54?source=rss-9f912e7eae81------2</link>
            <guid isPermaLink="false">https://medium.com/p/263d0a66ef54</guid>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Benjamin Wang]]></dc:creator>
            <pubDate>Mon, 18 Jan 2021 13:28:43 GMT</pubDate>
            <atom:updated>2021-01-18T13:43:03.676Z</atom:updated>
            <content:encoded><![CDATA[<h4>Various evaluation metrics are used for evaluating the effectiveness of a recommender. We will focus mostly on ranking related metrics covering HR (hit ratio), MRR (Mean Reciprocal Rank), MAP (Mean Average Precision), NDCG (Normalized Discounted Cumulative Gain).</h4><p>Recommender systems eventually output a ranking list of items regardless of different modelling choices. So it is important to look at how to evaluate directly ranking quality instead of other proxy metrics like mean squared error, etc.</p><h3>HR (Hit Ratio)</h3><p>In recommender settings, the hit ratio is simply the fraction of users for which the correct answer is included in the recommendation list of length <em>L.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2oVTjdyCRgJvfSSC9TDpw.png" /></figure><p>As one can see, the larger <em>L</em> is, the higher hit ratio becomes, because there is a higher chance that the correct answer is included in the recommendation list. Therefore, it is important to choose a reasonable value for <em>L.</em></p><h3>MRR (Mean Reciprocal Rank)</h3><p>MRR is short for <em>mean reciprocal rank.</em> It is also known as <em>average reciprocal hit ratio (ARHR).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzpFR1DToUSxBCDKJ4GSNA.png" /></figure><p>Note that there are different variations or simplifications for calculating <em>RR(u)</em>. <strong>For implicit dataset, the relevance score is either 0 or 1, for items not bought or bought (not clicked or clicked, etc.).</strong></p><p>Another simplification is only to look at <strong>one top relevant </strong>item in the recommendation list, instead of summing up for all. in case of implicit dataset, there is no ordering of relevance per se, it is sufficient just to consider any one relevant item on top of the list.</p><p><strong>One could argue that hit ratio is actually a special case of MRR, when <em>RR(u)</em> is binary, as it becomes 1 if there is a relevant item in the list, 0 otherwise.</strong></p><h3>MAP (Mean Average Precision)</h3><p>Let’s first refresh our memory on precision and recall, especially in the Information Retrieval are.</p><p><strong>What are precision and recall?</strong></p><p>In short, precision is the fraction of relevant items in all the retrieved items. It is used to answer how many items among all recommendations are correct.</p><p>And recall is the fraction of relevant items in all relevant items. It is to answer the coverage question, among all those considered relevant items, how many are captured in the recommendations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*6LJQQabNfdCACfM5xZg4sA.png" /><figcaption>Precision from <a href="https://en.wikipedia.org/w/index.php?title=Information_retrieval&amp;oldid=793358396#Average_precision">Wikipedia</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*imtOGI7xkbzLpMDoyGV_tw.png" /><figcaption>Recall from <a href="https://en.wikipedia.org/w/index.php?title=Information_retrieval&amp;oldid=793358396#Average_precision">Wikipedia</a></figcaption></figure><p><strong>What is precision@k?</strong></p><p>Building upon it, we can also define <strong>precison@k </strong>and also <strong>recall@k</strong> similarly. Precision@k would be the fraction of relevant items in the top k recommendations, and recall@k would be the coverage of relevant times in the top k.</p><p><strong>What is Mean Average Precision?</strong></p><p>Now back to MAP.</p><p><strong>MAP is the mean of <em>Average Precision.</em></strong> <strong>If we have the AP for each user, it is trivial just to average it over all users to calculate the MAP.</strong></p><p>By computing a precision and recall at every position in the ranked sequence of documents, one can plot a precision-recall curve, plotting precision <em>p(r) </em>as a function of recall <em>r</em>. Average precision computes the average value of <em>p(r) </em>over the interval from 0 to 1.</p><p>This is essential the area under the precision-recall curve. In a discrete manner, it can be calculated as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5WeY7ZsN3hHrU95sTGgMw.png" /></figure><p>We can finally calculate the MAP, which is simply the mean of AP over all users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*OnjrGNTPAwSVpIU-mZ55aA.png" /></figure><h3>NDCG (N<em>ormalized Discounted Cumulative Gain</em>)</h3><p>NDCG stands for <em>normalized discounted cumulative gain. </em>We will build up this concept backwards answering the following questions:</p><ul><li>What is gain?</li><li>What is cumulative gain?</li><li>How to discount?</li><li>How to normalize?</li></ul><p><strong>Gain</strong> for an item is essentially the same as the relevance score, which can be numerical ratings like search results in Google which can be rated in scale from 1 to 5, or binary in case of implicit data where we only know if a user has consumed certain item or not.</p><p>Naturally Cumulative Gain is defined as the sum of gains up to a position <em>k</em> in the recommendation list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*GEvXfCqT6hq_KNT_WMnRFA.png" /></figure><p>One obvious drawback of CG is that it does not take into account of <strong>ordering</strong>. By swapping the relative order of any two items, the CG would be unaffected. This is problematic when ranking order is important. For example, on Google Search results, you would obviously not like placing the most relevant web page at the bottom.</p><p>To penalize highly relevant items being placed at the bottom, we introduce the <strong>DCG</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*sb2sXH1RHQFgZgl4l9pCSw.png" /></figure><p>By diving the gain by its rank, we sort of push the algorithm to place highly relevant items to the top to achieve the best DCG score.</p><p>There is still a drawback of DCG score. It is that DCG score adds up with the length of recommendation list. Therefore, we cannot consistently compare the DCG score for system recommending top 5 and top 10 items, because the latter will have higher score not because its recommendation quality but pure length.</p><p>We tackle this issue by introducing <strong>IDCG (ideal DCG). </strong>IDCG is the DCG score for the most ideal ranking, which is ranking the items top down according their relevance up to position <em>k</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*cDC8roXZrP-iUeR1vlmGBQ.png" /></figure><p>And NDCG is simply to normalize the DCG score by IDCG such that its value is always between 0 and 1 regardless of the length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*OvlkhT6u2ROOdWPOhWWOHA.png" /></figure><h3>Notes</h3><ol><li>Wikipedia on NDCG is pretty good: <a href="https://en.wikipedia.org/wiki/Discounted_cumulative_gain">https://en.wikipedia.org/wiki/Discounted_cumulative_gain</a></li><li>Wikipedia has a very nice list of evaluation metrics used in IR: <a href="https://en.wikipedia.org/w/index.php?title=Information_retrieval&amp;oldid=793358396#Average_precision">https://en.wikipedia.org/w/index.php?title=Information_retrieval&amp;oldid=793358396#Average_precision</a></li><li>This article explains MAP very well both in IR and object detection: <a href="https://towardsdatascience.com/breaking-down-mean-average-precision-map-ae462f623a52">https://towardsdatascience.com/breaking-down-mean-average-precision-map-ae462f623a52</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=263d0a66ef54" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ranking-evaluation-metrics-for-recommender-systems-263d0a66ef54">Ranking Evaluation Metrics for Recommender Systems</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross Entropy Loss in PyTorch]]></title>
            <link>https://medium.com/swlh/cross-entropy-loss-in-pytorch-c010faf97bab?source=rss-9f912e7eae81------2</link>
            <guid isPermaLink="false">https://medium.com/p/c010faf97bab</guid>
            <category><![CDATA[cross-entropy]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <dc:creator><![CDATA[Benjamin Wang]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 15:09:40 GMT</pubDate>
            <atom:updated>2021-01-16T22:38:06.591Z</atom:updated>
            <content:encoded><![CDATA[<h3>Loss Functions in Machine Learning</h3><h4>A small tutorial or introduction about common loss functions used in machine learning, including cross entropy loss, L1 loss, L2 loss and hinge loss. Practical details are included for PyTorch.</h4><h3>Cross Entropy</h3><p>Cross entropy loss is commonly used in classification tasks both in traditional ML and deep learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/0*BxYO1LbZ40uuU2nG.jpeg" /><figcaption>Image from <a href="https://towardsdatascience.com/cross-entropy-loss-function-f38c4ec8643e">this post</a></figcaption></figure><p>Note: <em>logit</em> here is used to refer to the unnormalized output of a NN, as in <a href="https://developers.google.com/machine-learning/glossary/#logits">Google ML glossary</a>. However, admittedly, this term is overloaded, as discussed in this <a href="https://stackoverflow.com/questions/41455101/what-is-the-meaning-of-the-word-logits-in-tensorflow">post</a>.</p><p>In this figure, the raw unnormalized output from a Neural Network is converted into probability by a softmax function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*eKHqb8IjKL2oVTBE.jpeg" /><figcaption>Image from <a href="https://towardsdatascience.com/cross-entropy-loss-function-f38c4ec8643e">this post</a></figcaption></figure><p>Now suppose we have a training sample which is a dog, the target label would be [1,0,0,0] , while the NN raw output is [3.2, 1.3, 0.2, 0.8] , the softmax probability output is [0.775, 0.116, 0.039, 0.07] , what would be the cross entropy loss?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2E-C0iqdQL-JHkEiDqBqA.png" /></figure><p>Plugging in the values, we have the loss value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCYvYhq8596_4Aay20Pszg.png" /></figure><p>Note: natural log is used as common practice.</p><p>After some weights update, we have new raw outputs for the same sample, the softmax probability becomes [0.9, 0.05, 0.03, 0.02] , the new loss value is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yh9oci1e0uGkSNYPlbbHA.png" /></figure><p>This new loss is lower than previous loss, indicating NN is learning. Intuitively, we can also observe that the softmax probability is closer to the the true distribution.</p><p>The perfect loss will be 0, when the softmax outputs perfectly matches the true distribution. However, that would mean extreme overfitting.</p><p>Another practical note, in Pytorch if one uses the nn.CrossEntropyLoss <strong>the input must be unnormalized raw value (aka </strong><strong>logits)</strong>, <strong>the target must be class index instead of one hot encoded vectors</strong>.</p><p>See Pytorch documentation on <a href="https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html">CrossEntropyLoss</a>.</p><p>The same pen and paper calculation would have been</p><pre>from torch import nn<br>criterion = nn.CrossEntropyLoss()<br>input = torch.tensor([[3.2, 1.3,0.2, 0.8]],dtype=torch.float)<br>target = torch.tensor([0], dtype=torch.long)<br>criterion(input, target)<br>Out[55]: tensor(0.2547)</pre><p>Note the the input is the raw logits, and the target is the class index ranging from 0 to 3 in this case, representing dog, cat, horse, cheetah respectively.</p><p>Also in this example, we only considered a single training sample, in reality, we normally do mini-batches. And <strong>by default PyTorch will use the average cross entropy loss of all samples in the batch</strong>.</p><p>One might wonder, what is a good value for cross entropy loss, how do I know if my training loss is good or bad?</p><p>Some intuitive guidelines from <a href="https://machinelearningmastery.com/cross-entropy-for-machine-learning/">MachineLearningMastery post</a> for natural log based for a mean loss:</p><ul><li><strong>Cross-Entropy = 0.00</strong>: Perfect probabilities.</li><li><strong>Cross-Entropy &lt; 0.02</strong>: Great probabilities.</li><li><strong>Cross-Entropy &lt; 0.05</strong>: On the right track.</li><li><strong>Cross-Entropy &lt; 0.20</strong>: Fine.</li><li><strong>Cross-Entropy &gt; 0.30</strong>: Not great.</li><li><strong>Cross-Entropy &gt; 1.00</strong>: Terrible.</li><li><strong>Cross-Entropy &gt; 2.00</strong> Something is broken.</li></ul><p><strong>Binary cross entropy</strong> is a special case where the number of classes are 2. In practice, it is often implemented in different APIs. In PyTorch, there are nn.BCELoss and nn.BCEWithLogitsLoss . The former requires the input to be normalized sigmoid probability, whereas the latter can take raw unnormalized logits.</p><h4>Root Mean Squared Error and others</h4><p>MAE is for <em>Mean Absolute Error</em>, MSE for <em>Mean Squared Error</em> and RMSE for <em>Root Mean Squared Error</em>.</p><p><a href="http://zerospectrum.com/2019/06/02/mae-vs-mse-vs-rmse/">This post provides a concise overview of MAE, MSE and RMSE</a>.</p><p>MAE is also known as L1 Loss, and MSE is also known as L2 Loss.</p><h3>Hinge loss</h3><p>Hinge loss is commonly used for SVM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*CwH18QfyhGoZeEIi.png" /><figcaption>Image source: <a href="https://towardsdatascience.com/a-definitive-explanation-to-hinge-loss-for-support-vector-machines-ab6d8d3178f1">post</a></figcaption></figure><p>This loss is used for max margin classifier, such as SVM. Suppose the boundary is at origin:</p><ul><li>If an instance is classified correctly and <em>with sufficient margin (distance &gt; 1), </em>the loss is set to 0</li><li>If an instance is classified correctly <em>but very close to the margin</em> (0&lt;distance&lt;1)</li><li>If an instance is miss classified, a positive loss is used as penalty proportional to the distance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*Icw0F3rjTSWO_rE-FLx7Xw.png" /><figcaption>From <a href="https://en.wikipedia.org/wiki/Hinge_loss">Wikipedia</a></figcaption></figure><p>where <em>t </em>represents the true label (in SVM, we use -1 and +1 to label two different classes), <em>y</em> represents the prediction score (raw output of the model, similar to logit), <strong>which can be intuitively understood as how far the prediction is from the boundary</strong>.</p><p>If both <em>t</em> and <em>y </em>are of the same sign (t*y &gt; 0), the classification results are correct. however, as explained, for those 0&lt;t*y &lt;1, we still induce a small penalty because they are too close to the boundary.</p><p>If t*y &lt; 0, meaning the classification is wrong, a positive loss is used as penalty proportional to the distance <em>y.</em></p><h3>Notes</h3><ol><li>Cross entropy part of this blog draws many inspirations from: <a href="https://towardsdatascience.com/cross-entropy-loss-function-f38c4ec8643e">https://towardsdatascience.com/cross-entropy-loss-function-f38c4ec8643e</a></li><li>Hinge loss part uses <a href="https://towardsdatascience.com/a-definitive-explanation-to-hinge-loss-for-support-vector-machines-ab6d8d3178f1">https://towardsdatascience.com/a-definitive-explanation-to-hinge-loss-for-support-vector-machines-ab6d8d3178f1</a> as reference</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c010faf97bab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/cross-entropy-loss-in-pytorch-c010faf97bab">Cross Entropy Loss in PyTorch</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monte Carlo Tree Search: An Introduction]]></title>
            <link>https://medium.com/data-science/monte-carlo-tree-search-an-introduction-503d8c04e168?source=rss-9f912e7eae81------2</link>
            <guid isPermaLink="false">https://medium.com/p/503d8c04e168</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[alphago]]></category>
            <category><![CDATA[monte-carlo-tree-search]]></category>
            <category><![CDATA[breadth-first-search]]></category>
            <dc:creator><![CDATA[Benjamin Wang]]></dc:creator>
            <pubDate>Sun, 10 Jan 2021 15:46:23 GMT</pubDate>
            <atom:updated>2021-01-11T18:40:34.830Z</atom:updated>
            <content:encoded><![CDATA[<h4>MCTS is the cornerstone of AlphaGo and many AI applications. We aim to build some intuitions and along the way get our hands dirty.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Wv4gteWiNUUvm7gw" /><figcaption>Monte Carlo (Image from <a href="https://unsplash.com/photos/1CkSNmbT7J0">Unsplash</a>)</figcaption></figure><p>Monte Carlo Tree Search (MCTS) is an important algorithm behind many major successes of recent AI applications such as AlphaGo’s striking showdown in 2016.</p><p>In this blog, we will first start with <em>uninformed search</em> in which we simply traverse through the whole search space to find the optima. It includes <strong>depth-first search </strong>and <strong>breadth-first search</strong>.</p><p>Then we follow by describing how MCTS algorithm works. In the end, we apply it to a toy example problem of finding the most rewarding leaf node of a binary tree.</p><h3>Uninformed search</h3><p>Uninformed search, as its name suggests, is a kind of generic search algorithms which are given no extra information other than an abstract problem definition. Although they can be applied universally with the right abstraction of problems, they normally suffer from efficiency problem when problem becomes large.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*pGvGBWbAn61ZFxxh.png" /><figcaption>DFS and BFS (<a href="https://dev.to/danimal92/difference-between-depth-first-search-and-breadth-first-search-6om">image source</a>). An intuitive implementation in my own Github repo <a href="https://github.com/wlongxiang/mcts/blob/main/uninformed_tree_search.py">wlongxiang/mcts</a>.</figcaption></figure><p>A tree with branch factor of <em>b </em>and depth of <em>d </em>would have b^d (read as <em>b </em>to the power of <em>d</em>) number of leaf nodes.</p><p>In games, we use a so-called game tree where each node represents a state of a game and its children nodes represent possible next states for all possible actions a player can take.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zZdO6w2GJnpR1O5l.png" /><figcaption>A game tree of tic-tac-toe (<a href="https://www.ques10.com/p/12787/draw-game-tree-for-a-tic-tac-toe-problem-1/">image source</a>). Note that it is not fully expanded due to space.</figcaption></figure><p>To give some ideas, Go has averaging branch factor of 250 according to <a href="https://en.wikipedia.org/wiki/Branching_factor">Wikipedia</a>. Some back of the envelope calculation will quickly show how prohibitive it is to use uninformed search in Go:</p><ul><li>At step 1: 250</li><li>At step 2: 250² = 62500</li><li>At step 3: 250³ = 15,625,000</li><li>At step 4: 250⁴ = 3,906,250,000</li><li>At step 5: 250⁵ = 976,562,500,000</li><li>…</li><li>At step 10: 250¹⁰ = 953,674,316,406,250,000,000,000</li></ul><p>After 10 steps, we already see a cosmetic number of possible states of game. This also gives some sense why the win of AlphaGo is such a milestone for humankind.</p><h3>Monte Carlo Tree Search</h3><p>Now we understand the fact that we need something <strong>smarter</strong> than uninformed search to navigate through a gigantic state space like the game of Go. MCTS is one such smart algorithm that gives us a way out.</p><p>Essentially, <strong>MCTS uses Monte Carlo simulation to accumulate value estimates to guide towards highly rewarding trajectories in the search tree</strong>. In other words, MCTS pays more attention to nodes that are more promising, so it avoids having to brute force all possibilities which is impractical to do.</p><p>At its core, MCTS consists of repeated iterations (ideally infinite, in practice constrained by computing time and resources) of 4 steps: <strong>selection, expansion, simulation and backup.</strong></p><h4>Selection</h4><p>In this step, we use <em>tree policy</em> to construct path from root to most promising <em>leaf node</em>.</p><p>A leaf node is a node which has unexplored child node(s).</p><p>A tree policy is an informed policy used for action (node) selection in the <em>snowcap</em> (explored part of the game tree as opposed to the vast unexplored bottom part). One important consideration of such policy is the balance of <strong>exploration vs exploitation, </strong>a recurring topic in AI, especially in Reinforcement Learning.</p><p>In the algorithm behind AlphaGo, a UCB based policy is used. More specifically, each node has an associated UCB value and during selection we always chose the child node with the highest UCB value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHoY3vvKlW3sszxBmkABsA.png" /></figure><p>As we can see, the more a node <em>i </em>is visited, the lower the second term in UCB becomes, hence decreasing its probability of being selected again. Therefore, UCB algorithm has exploration and exploitation inherently built-in. Smart and neat!</p><p>For a more rigorous yet still easy-to-follow account of exploration vs exploitation (including UCB), please read<a href="https://lilianweng.github.io/lil-log/2018/01/23/the-multi-armed-bandit-problem-and-its-solutions.html"> Lilian Weng’s blog</a> on this topic.</p><p>Finally, in the selection step, we can traverse the snowcap or explored part of the tree until a leaf node has been reached.</p><h4>Expansion</h4><p>Remember that we reach a leaf node at the end of selection?</p><p>In expansion step, we simply randomly pick an unexplored node of a leaf node.</p><h4>Simulation (or Roll-out)</h4><p>During this step, we roll out one or multiple simulations with reward accumulated for each simulation. Roll-out policy is normally simply or even pure random such that it is fast to execute. For example, a win might induce reward of +1, a draw for 0, and a loss for -1.</p><p>One might ask, why bother?</p><p>In the game of Go, this step is like the algorithm, like a Go master might do in his/her head, playing many times of the game until it’s end. <strong>The truly genius not only sees the future, but many versions of it.</strong></p><h4>Backup</h4><p>Now we have played out many simulations, what can we do with it to inform the best next move?</p><p>We use the accumulated rewards of simulations to back up and update the values of nodes in the <em>snowcap</em>.</p><p>Note: we don’t update the values of nodes during the roll-out steps! This is done so because we need to focus on the vicinity of the root node (snowcap), based on which we need to make decisions of next move(s). Whereas the values outside of snowcap is not relevant for such decision, nor computationally efficient to store and calculate.</p><h4>Put it together</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*llm1_-xWFdE0rCBGmte4sA.png" /><figcaption>Image from An Introduction: Reinforcement Learning by Sutton &amp; Barto</figcaption></figure><p>The pseudo-code might look like below:</p><pre>def run(node, num_rollout):<br>    <em>&quot;one iteration of select-&gt;expand-&gt;simulation-&gt; backup&quot;<br>    </em>path = select(node)<br>    leaf = path[-1]<br>    expand(leaf)<br>    reward = 0<br>    for i in range(num_rollout):<br>        reward += simulate(leaf)<br>    backup(path, reward)</pre><p>Note that this is one iteration of MCTS given a specific root node, e.g., a node in the game tree. In practice, we can do as many iterations as possible of these 4 steps, during which in the simulation step multiple rollouts can be done. After computation time or resources are exhausted, we stop the iteration loop, and decide what is the next move to take, then we end up with a new root node, and run the iterations again, so on and so forth…</p><h3>A simple but not simpler example</h3><p>(Code available at: <a href="https://github.com/wlongxiang/mcts">git repo</a>)</p><p>Let’s suppose, we have a binary tree of depth 7, all of its leaf nodes carry a certain reward between 0 and 100, drawn from uniform distribution. Our task is to find the highest reward among the 2⁷ leaf nodes (a small note: leaf nodes used here are of its rudimentary meaning, that is the nodes in the tree without children, unlike in MCTS we use leaf nodes to denote nodes with unexplored child).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nTkon2eZDMcVomkh.png" /><figcaption>An example binary tree with depth = 7, created by following <a href="https://tex.stackexchange.com/questions/203399/drawing-binary-trees-with-latex-labels">instruction</a></figcaption></figure><p>The reader can checkout my <a href="https://github.com/wlongxiang/mcts">git repo</a>, and run find_max_leaf_binary_tree.py. The code handily includes a few parameters:</p><ul><li>numb_iter to change number of MCTS iterations</li><li>num_rollout to change number of roll-outs during simulation</li><li>exploration_weight to control the balance between exploration and exploitation</li></ul><p>Enough to play with!</p><p>The default run shows results below:</p><pre>Expected (max) leaf node: node@7_53, value: 99.16984625936269<br>Expected (min) leaf node: node@7_121, value: 1.2521064278136151<br>Found optimal (max) leaf node: node@7_104, value: 95.8546572417074</pre><p>Not too bad, the found optimal node is pretty close to its expected value (note you might not get the exact result due to its probabilistic nature).</p><h3>Conclusion</h3><p>Many of AI problems have its roots in search problems. After all, life is about searching. Hope you all find your optimal path :).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=503d8c04e168" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/monte-carlo-tree-search-an-introduction-503d8c04e168">Monte Carlo Tree Search: An Introduction</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matrix Factorization in Recommender Systems]]></title>
            <link>https://medium.com/data-science/matrix-factorization-in-recommender-systems-3d3a18009881?source=rss-9f912e7eae81------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d3a18009881</guid>
            <category><![CDATA[latent-factor-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[matrix-factorization]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Benjamin Wang]]></dc:creator>
            <pubDate>Tue, 05 Jan 2021 21:55:15 GMT</pubDate>
            <atom:updated>2021-01-10T16:05:35.722Z</atom:updated>
            <content:encoded><![CDATA[<h4>A gentle intro into Matrix Factorization techniques in Recommender Systems, including<em> </em><strong>FunkSVD , SVD++, and Non-negative Matrix Factorization</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*zbvXub__tudmX0ay" /><figcaption>You mean this Matrix? (image source: <a href="https://unsplash.com/photos/iar-afB0QQw">Unsplash</a>)</figcaption></figure><h3>Introduction</h3><p>RS is to match items to users. The starting point is a user-item matrix filled with values representing either explicit feedback (user provided ratings) or implicit feedback (count of clicks, number of visits, watch time, etc.). One can also pose this question as a matrix filling problem: <strong>given the known entries in user-item matrix, how to fill in the missing entries given all sort of constraints?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*9wyiY3Tbg9ngxC9bUAt-DA.png" /><figcaption>An example ratings matrix of fruits (image by author)</figcaption></figure><p>Collaborative filtering methods have achieved tremendous success in this area. The two most prominent methods are model based and neighborhood based methods. By model-based methods, we mainly refer to <strong>latent factor models, where MF techniques are used.</strong></p><p>Both approaches exploit the <strong>correlations</strong> in the data matrix. For example, in user-based neighborhood methods, user-wise correlations are leveraged to make peer groups and hence complete missing ratings in the matrix, whereas item-based neighborhood methods leverage item-wise correlations. <strong>Latent factor models transform both users and items into the same latent space in one shot. </strong>Therefore, they leverage both users and items correlations at the same time, hence are more effective generally.</p><h3>Funk-SVD</h3><p>Funk-SVD is attributed to Simon Funk in the Netflix prize contest. <strong>Note</strong>: strictly speaking, the “SVD” in the name is not correct. SVD as in linear algebra is much different from matrix factorization as done here, <a href="https://www.freecodecamp.org/news/singular-value-decomposition-vs-matrix-factorization-in-recommender-systems-b1e99bc73599/#:~:text=In%20fact%2C%20SVD%2B%2B%2C%20as,an%20extension%20of%20Funk&#39;s%20work.&amp;text=Note%20that%2C%20despite%20its%20name,applications%2C%20including%20PCA%20and%20RS.">see why the confusion</a>.</p><p>It factors the user-item matrix into the product of two lower rank matrices as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*qKQb-vGa7cpVQXBKbLKI5A.png" /></figure><p>Where <strong>R </strong>is the approximated rating matrix of <em>m </em>rows and <em>n</em> columns, <strong>U is a user-factor matrix </strong>, it has a row for each user (called <strong>user factor</strong> uᵢ), <strong>Vᵀ is a item-factor matrix, </strong>it has a column for each item (called <strong>item factor</strong> vⱼ)</p><p>Therefor, suppose the latent dimension is <em>k</em>, any rating in R is approximated by the <strong>dot product</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*vKGjnDcQfTOZqfrRbFesFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*p2mo-NW-CCSEzbAbDhUEPQ.png" /></figure><p>Note that U has dimensions (m, k), while V is of dimensions (n, k).</p><p>How can we determine U and V? We can solve it as an optimization problem (including regularization to avoid overfitting, or extreme values in U and V) just like many machine learning problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoOSUzyIC6qojrdDgkV5tg.png" /></figure><p>This problem can be solved in standard manner by SGD by calculating the derivative of <em>J </em>with respect to both user factor uᵢ and item factor vⱼ respectively.</p><h3>SVD++</h3><p>SVD++ is an extension of Funk-SVD to incorporate <strong>implicit feedback data</strong>.</p><p>Implicit feedback is any side information that we can use to infer users preference about certain items, such as clicks, visits, how much time spent on a TV program, etc. Even in case of explicit rating matrix, the identity of the rating matrix can be seen as implicit feedback. In other words, <strong>simply the act that a user chooses to rate an item no matter high or low, carries strong predictive signal.</strong></p><p>Now, let’s see how we can derive an <strong>implicit feedback matrix</strong> F from an explicit ratings matrix R:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbgDEEVya8IMoEGK--Uylg.png" /></figure><p>where we simple assign 1 if there is rating present regardless of its value, otherwise 0. Then, we normalize the identities to make the L2-norm of each row to be 1.</p><p>However, it is worth to note that the implicit feedback matrix can be any kind of unary matrix (unary in the sense that it contains only 0s and positive numeric), e.g., number of times a user clicks on an item on Amazon.</p><p>Now the reconstructed R matrix is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*8PjH3QUl7_5L-gArRyQmTw.png" /></figure><p>which contains an additional component introduced by the implicit matrix F, and a companion <strong>implicit item factor matrix Y, which needs to be learned by SGD from the data.</strong></p><p>Note that F has same dimensions as R of (m, n), while Y is (n, k), the same dimension as V, the explicit item-factor matrix.</p><p><strong>Intuitively, the implicit item factor matrix Y encodes a user’s preference for certain genres inferred from the very action of caring to give a rating to a certain item j.</strong></p><p>The way to learn U, V and Y are the same as in Funk-SVD, it is just that now we have more parameters, an extra Y matrix to learn.</p><h3>Non-negative Matrix Factorization</h3><p>NMF are similar to a Funk-SVD except that we now have additional constrains for U &gt; 0 and V &gt; 0, which requires all elements in the user-factor and item-factor matrix to be always positive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*0swjAIAOXbPgPXKVcdbvdg.png" /></figure><p>As we can see, it is the same as Funk-SVD, except the addition constrains. So, it can also be solved in the same manner using optimization techniques.</p><p>The main advantage of this approach is <strong>interpretability. </strong>Because now, we can easily interpret the values in U and V to be preference for certain latent factors. In case of movies, user factors can be understood as a combination of preference for “action”, “romance”, whereas item factors can also be seen as a weighted combination of different genres.</p><h3>Closing Words</h3><p>Latent factor models are very effective for encoding users and items into latent space. As pointed out by Yehuda Koren in his paper [1]:</p><blockquote><strong>Neighborhood models are most effective at detecting very localized relationships</strong>. They rely on a few significant neighborhood relations, often ignoring the vast majority of ratings by a user. Consequently, these methods are unable to capture the totality of weak signals encompassed in all of a user’s ratings. <strong>Latent factor models are generally effective at estimating overall structure that relates simultaneously to most or all items</strong>. However, these models are poor at detecting strong associations among a small set of closely related items, precisely where neighborhood models do best.</blockquote><p>As in many cases, the sweet spot is somewhere in between by combining the best of both worlds.</p><h3>References</h3><p>[1] <em>Factorization Meets the Neighborhood: a Multifaceted Collaborative Filtering Model by Yehuda Koren, 2008.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d3a18009881" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/matrix-factorization-in-recommender-systems-3d3a18009881">Matrix Factorization in Recommender Systems</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Back to Basics: Nearest Neighbours]]></title>
            <link>https://medium.com/data-science/back-to-basics-nearest-neighbours-676d6f11a31?source=rss-9f912e7eae81------2</link>
            <guid isPermaLink="false">https://medium.com/p/676d6f11a31</guid>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Benjamin Wang]]></dc:creator>
            <pubDate>Mon, 04 Jan 2021 16:23:10 GMT</pubDate>
            <atom:updated>2021-01-06T23:08:11.025Z</atom:updated>
            <content:encoded><![CDATA[<h4>We go back to the basics and look at Nearest Neighbour methods in the context of density estimation and recommender systems</h4><h3>Introduction</h3><p>Given the recent hyped progress in deep learning based approaches in AI research especially in NLP and CV, it is time to go back to the fundamentals. Many of the fundamental methods, such as neighbourhood based methods are surprisingly effective in many areas, even today. We take a brief look at nearest neighbour method and its applications in density estimation and recommender systems. User-based and item-based collaborative filtering are discussed. In the end, the cold start and data sparsity issue are also touched upon.</p><h3>Nearest Neighbour in the context of density estimation</h3><p>Let’s start with the problem of <a href="https://scikit-learn.org/stable/modules/density.html#density-estimation">density estimation</a>. In plain words, <strong>density estimation</strong> is the construction of an estimate, based on observed data, of an unobservable underlying probability density function. It can be used to gain insights into your data at hand, even better, it can also be utilized to generate synthetic data.</p><p>One most common method of density estimation is simply <strong>histogram</strong>, in which we count the number of points within a bin, and use the tally to visualize the underlying distribution. The main disadvantage with histogram is that it is very sensitive to bin selection both in terms of bin size and bin position. Readers can refer to <a href="https://scikit-learn.org/stable/auto_examples/neighbors/plot_kde_1d.html">scikit-learn documentation</a> for better illustrations.</p><p>A more sophisticated method is to use a <strong>kernel</strong> (e.g. Gaussian kernel) in place of a simple tally count, and a Parzen window to replace a naive bin. A Parzen window can be intuitively understood as a defined region surrounding a data point. <strong>The detailed mathematics is left out intentionally to focus on intuitions. </strong>The main idea remains similar to histogram, we still try to estimate the probability density using neighbour points in a region (instead of a bin) using a kernel (instead of simple tally) to smooth the distribution.</p><p>For more information on kernel density estimation, please refer to PRML by Bishop in Chapter 2 or a more <a href="https://scikit-learn.org/stable/modules/density.html#density-estimation">practical guide</a>.</p><p>In kernel density estimation methods, the region is fixed, while the number of neighbour points can vary depending on local data sparcity. Another approch is to fix the number of neighbour points K, and expand the region until K points are included. This approach is called <strong>K-Nearest Neighbours (KNN).</strong></p><p>KNN methods (also kernel density estimation) are a form of <strong>non-parametric </strong>methods in that it doesn’t assume an underlying distribution on training data. Instead, it “remembers” the whole training data, hence it is also called “<strong>memory based methods</strong>”. When KNN is applied to classification, it finds the nearest neighbours, or in other words, most similar training data points by predefined similarity measure (more on this later), and use the labels of neighbour points to determine the prediction results by majority vote, for example.</p><p>Some also tag KNN as “<strong>instance-based learning</strong>” or “<strong>lazy learning</strong>”, because it does not need any training process to fit the training data, the heavy-lifting calculation is delayed until prediction, and prediction is made based on a few instances in the neighbourhood of prediction sample. As we will see later, in real world implementation, some engineering optimization can be made to alleviate this issue.</p><h3>Advantages and Disadvantages</h3><p>It is always about trade-offs in the world of algorithms.</p><p><strong>Advantages:</strong></p><ul><li>Simple and intuitive</li><li>Highly versatile (one can choose variety of similarity metric combined with feature engineering to achieve a lot)</li></ul><p><strong>Disadvantages:</strong></p><ul><li><strong>High space complexity</strong>, because it needs to “memorize” the whole training data</li><li><strong>High time complexity during prediction</strong>, because it needs to exhaustively search through all training samples to form a neighbourhood</li></ul><p>There also exist many remedies to tackle above disadvantages. One method is to use an <strong>offline phase</strong> to pre-calculate similarity score and store intermediate results, which can be fetched efficiently later during online phase.</p><p>For a dataset of size N and dimension D, the computation cost to calculate similarity of all pairs of samples are O(DN²). Using the <a href="https://scikit-learn.org/stable/modules/neighbors.html#k-d-tree">K-D tree</a>, the complexity is reduced to O(DNlogN), which is significant improvement when N is large.</p><p>Actually, many libraries out there, scikit-learn being the most popular example, already does this by building an efficient data structure during the training phase. Once the fit method is called, depending on the algorithm selection (sklearn offers kdtree, balltree, bruto). If you are looking even faster implementations of such index, check out this <a href="https://towardsdatascience.com/make-knn-300-times-faster-than-scikit-learns-in-20-lines-5e29d74e76bb">blog post</a>.</p><h3>Nearest Neighbour in the context of Recommenders</h3><p>For those interested, the best paper from 2019 RecSys, a top conference of recommender systems shed some lights on some of the issues with deep learning research in this area [1]. And it turns out, neighbourhood based approaches are still forming a strong baseline.</p><p>KNN methods are used in collaborative filtering (CF) algorithms in recommender systems. <strong>At the core of CF is how to find similar users or items to form a peer group or neighbourhood</strong>.</p><p>There are two symmetrical methods of neighbourhood based CF in recommenders, namely, user-based CF and item-based CF.</p><p>As shown below, in a fruit store where users’ consumer patterns are logged, the goal is to recommend fruit to Bob.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ov0Hau_8BUrIUOEcgC92VA.png" /><figcaption>Adapted from the Internet (unknown source)</figcaption></figure><p>In the <strong>user-based </strong>approach on the left, Alice is considered similar to our target user (in reality, we normally identify a group of similar users), because they both like watermelon and strawberry in their consumption behaviour. Therefore, based on the assumption that similar users share similar fruit taste, we recommend grapes and orange to Bob because those are bought by him peers, but hasn’t been bought by him.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*dNdD4IvQuJZaLKbEXQHSig.png" /><figcaption>User-based CF matrix (image by author)</figcaption></figure><p>In the <strong>item-based</strong> approach on the right, we<strong> look for similar items to the item that has been bought by the target user</strong>. In this case, Bob has bought watermelon, and watermelon is most similar to grapes because they are bought by many overlapping users (both Alice and Eve). Therefore, grapes are recommended.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*Ua4NNqNzVGQrMabp8EQYeQ.png" /><figcaption>Item-based CF matrix (image by author)</figcaption></figure><p>As we have seen, the most vital part of both item-based and user-based CF methods is to choose the right similarity metric and form neighbourhoods.</p><p>Some of the similarity metrics are:</p><ul><li>Euclidian similarity</li><li>Cosine similarity</li><li>Discounted cosine similarity</li><li>Correlation based similarity (Pearson)</li><li>Jacaard similarity</li><li>etc.</li></ul><p>Apart from the problems mentioned previously about KNN methods in general regarding space and time complexity, other issues arise in the application area of recommender systems.</p><p>Two main issues are:</p><ul><li><em>Cold start: </em>this problem occurs when new items or users are added to the matrix, it turns out an <strong>empty vector, </strong>making it hard to calculate similarities and neighbours, hence almost impossible to generate recommendations.</li><li><em>Data sparcity: </em>even in the toy example above, we already observed sparcity issue where some entries in the matrix are missing, leading to inaccurate similarity calculations, degrading recommendations qualities. In a Web store with large number of items and users, one user can only interact with a small fraction of items, the matrix is intrinsically sparse.</li></ul><p>There are many ways to alleviate the issues above:</p><ul><li>As an easy resort, the system can be bootstrapped by <strong>recommending the most popular items</strong> to new users, however, this loses the appeal of personalisation.</li><li>Another typically employed method is to use some sort of “active learning” to provide incentive users to enter ratings or implicit feedbacks (clicks, like/dislike buttons, etc.) to populate the system.</li><li>One somehow controversial way is to leverage side information such as <strong>social network analysis</strong> to recommend items based on a user’s social circle if such side information is accessible. <strong>The base assumption here is that friends have similar tastes, and recommend items to each other in real life. </strong>A reference paper on the usage of side information is in [4].</li><li>Use model based methods, such as Matrix Factorisation, which inherently deals with the <em>data sparsity </em>issue, because it does MF based on existing available ratings. However, this doesn’t really solve the issue, because it still impacts the accuracy of the model due to limited data available. For MF methods, a nice tutorial is written in [5]. A more complete account on more advanced MF on implicit dataset and NMF are described in Aggarwal’s “<em>Recommender Systems: the Textbook</em>”.</li></ul><h3>References</h3><p>[1] “Are We Really Making Much Progress? A Worrying Analysis of Recent Neural Recommendation Approaches”, <a href="https://arxiv.org/abs/1907.06902">https://arxiv.org/abs/1907.06902</a></p><p>[2] “Recommender Systems: the Textbook” by Aggarwal</p><p>[3] Tables made with <a href="https://www.tablesgenerator.com/markdown_tables">https://www.tablesgenerator.com/markdown_tables</a></p><p>[4] “Research Commentary on Recommendations with Side Information: A Survey and Research Directions”, <a href="https://arxiv.org/abs/1909.12807">https://arxiv.org/abs/1909.12807</a></p><p>[5] blog: <a href="https://albertauyeung.github.io/2017/04/23/python-matrix-factorization.html">https://albertauyeung.github.io/2017/04/23/python-matrix-factorization.html</a> and code: <a href="https://github.com/albertauyeung/matrix-factorization-in-python">https://github.com/albertauyeung/matrix-factorization-in-python</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=676d6f11a31" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/back-to-basics-nearest-neighbours-676d6f11a31">Back to Basics: Nearest Neighbours</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Work: A Scarcity in Digital Age]]></title>
            <link>https://medium.com/swlh/deep-work-a-scarcity-in-digital-age-93c133bbf500?source=rss-9f912e7eae81------2</link>
            <guid isPermaLink="false">https://medium.com/p/93c133bbf500</guid>
            <category><![CDATA[deep-work]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Benjamin Wang]]></dc:creator>
            <pubDate>Mon, 21 Dec 2020 22:44:10 GMT</pubDate>
            <atom:updated>2021-01-08T21:41:45.138Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep work is valuable, rare and even meaningful in a digital world full of noise and distraction. Now, quit social media and embrace boredom.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*1zR1IJCzm1SQjlPUNwNNOA.png" /><figcaption>Illustration by <a href="https://dribbble.com/thierryfousse">Thierry Fousse</a> from <a href="https://icons8.com/">Icons8</a></figcaption></figure><h3>Introduction</h3><p>Yuval Noah Harari, the author of <em>Sapiens </em>(an international bestselling phenomenon), has no smartphone. However, that doesn’t stop him from making bold and insightful and somewhat provocative predictions about our very future of humanity and how AI and bio-technologies could join hands and shape history. By the way, he does 2 hour meditation every day and 2 month of retreat every year.</p><p>Bill Gates, a name that needs no introduction, would escape from daily routines and go into secret cabin where no distractions of any communication tools or people are present to think about “big ideas” in innovation and strategies about Microsoft. This is what he calls “Think weeks”.</p><p>The list just goes on and on…</p><p>The ubiquity of deep focus among influential individuals (more ironically so among those who are behind the big tech companies) is important to emphasize because it stands in sharp contrast to the behaviors of most modern Internet users and knowledge workers, who are by a large chance reading this blog from their smart phones right now.</p><p>As I will define and argue later, deep work is not just valuable and rare from pragmatic perspective, but also meaningful in a world where <em>meaning</em> is at worst non-existent, at best ill-defined.</p><h3>Definitions</h3><p>According to Cal Newport, the author of <em>Deep Work.</em> Deep work is defined as:</p><blockquote><strong>Deep work: </strong><em>Professional activities performed in a state of distraction-free concentration that push your cognitive capabilities to their limit. These efforts create new value, improve your skill and are hard to replicate.</em></blockquote><p>Whereas in contrast, shallow work is defined as:</p><blockquote><strong>Shallow work:</strong> <em>Non-cognitively demanding, logistical-style tasks, often performed while distracted. These efforts tend to not create much new value in the world and are easy to replicate.</em></blockquote><p>If you prefer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GBMxNLVgtzQRbe6gMGG7sg.png" /><figcaption>Deep work v.s. Shallow work</figcaption></figure><h3>Deep work is valuable</h3><p>The world is flat. It is increasingly connected and automated by the inevitable rise of Internet, and now data and AI.</p><p>In the “brave” new world (quote is mine, since I believe we are inching towards Aldous Huxley’s distopia), Cal Newport argues there are three types of winners:</p><ul><li><strong>High-skill workers </strong>those<strong> </strong>who can work well and creatively with intelligent machine</li><li><strong>Superstars </strong>those who are best in what they do, whatever the field</li><li><strong>Owners</strong> those who have access to capital</li></ul><p>Not everyone is born with a silver spoon. However, the former two are attainable if one poses two core capabilities:</p><ul><li><strong>The ability to <em>quickly</em> master hard things</strong></li><li><strong>The ability to produce at elite level in terms of both quality and speed</strong></li></ul><p>This is the kind of person with high I/O bandwidth, who inputs fast and outputs fast and with quality.</p><p>To master intelligent machines is hard, to be at the best of what you do is hard, to <strong>quickly </strong>learn hard things is hard squared, to produce at elite level is hard exponential.</p><p>How to thrive in the new economy? It can only be done through laser-focused deep work.</p><h3>Deep work is rare</h3><p>Deep work is rare in today’s business world. Cal Newport lists three trends as causes:</p><ul><li>The ubiquity of open office, which might create more serendipity at the cost of massive distraction</li><li>The rise of instant messaging tools and the implicit and sometimes explicit expectations of <strong>always online</strong></li><li>The push for active presence on social media for content producers (for example, journalist)</li></ul><p>This phenomenon highlights a paradox. If deep work is so valuable, why are not organizations encouraging it?</p><p>One reason is that it is hard to measure productivity of today’s white-collar jobs. In the mechanical industrial age, a worker’s productivity is simply the number of items he/she produces in a unit of time. Arguably, we can also measure a software engineer’s output by the number of code he/she writes. However, I can most surely say this metric can easily go in totally wrong direction, because the best engineers are typically not those who produce the most lines of code. This <strong>non-linearity </strong>of these jobs lead to a metric blackhole prevalent today.</p><p>This metric black hole together with the law of least resistance (in other words, people are lazy, so does the business world) creates another strange scene:</p><blockquote><strong><em>Busyness as proxy for productivity</em>: </strong>In the absence of clear indications of what it means to be productive and valuable in their jobs, many knowledge workers turn back toward an industrial indicator of productivity: doing lots of stuff in a visible manner.</blockquote><p>Many people are terrified by an empty work schedule and checking their emails every instant, as if being busy is the only reason why they are hired.</p><p>Another reason behind this rareness of deep work is the cult belief in Internet. <strong>Anything Internet is good, anything Internet is innovation, anything silicon valley does is good for my business. “This is how Google does it” is becoming a toxic dogma in many companies, even though what they do is thousands miles far from what Google is doing.</strong></p><p>This <strong>Internet-centrism </strong>pushes the whole business world and every individual online and always connected. To stay offline is not a default anymore, even morally unethical to some in today’s work culture.</p><h3>Deep work is meaningful</h3><blockquote>“I will live the focused life, because it is the best kind there is.”</blockquote><blockquote>— Winifred Gallagher</blockquote><p>From the perspective of neurology, to increase the time you spend in a <strong>state of depth </strong>is to leverage the complex machinery of human brain in a way that maximises the meaning and satisfaction that you will associate with working life.</p><p>From the perspective of psychology, deep work is an activity well suited to generate a <strong>flow state</strong> in one’s mind, which in turn generates happiness.</p><p>Even from a philosophical point of view, deep work can help modernity reestablish meaning, in a world where god is absent and sacredness is vanishing in every minute spent on TikTok.</p><p><strong>Meaning is found through craftsmanship, and deep work is the only way leading there.</strong></p><p>Software engineers find meanings in code. Beautiful code is concise and poetic for those who appreciate the craft.</p><h3>How to achieve deep work?</h3><p>Deep work is a skill that requires training. However, there are many different roads leading to Rome.</p><p>Some prefer the so-called “monastic” approach or caveman approach if you can afford cutting off all connections at all times.</p><p>Others adopt a bimodal approach, Yuval Noah Hararri and Bill Gates as mentioned before are prototypical examples.</p><p>For most of average people, who can simply not afford such luxuries to cut off everything for more than a week or even a few days, a rhythmic approach is perhaps much more pragmatic. This methodology can be summarised as “<strong>You are either in it or not.</strong>” or “<strong>When you work, work hard. When you are done, be done.</strong>”</p><p>One’s <em>will power </em>is a limited resource, the more you use it, the less it becomes. This principle tells us to minimize distractions in our surroundings, because every time you use your will power to resist the temptation to pick up your smartphone, you exhaust some will power from your reserve.</p><p><strong>Quit social media.</strong> Social media is sophisticated engineered to capture your attention and time, which in other words is the largest consumer of your will power, by quitting it you eliminate the biggest roadblock to deep work.</p><p><strong>Embrace boredom.</strong> Nowadays, people cannot stand a single boring moment, not during the two minutes waiting in queue, not during an elevator ride, not even during a moment of silence at a dinner with close friends or partner.</p><p>Resist the source of temptation in your pocket and embrace boredom next time you encounter it, you might give yourself an otherwise scarce opportunity for new ideas to manifest themselves.</p><h3>References</h3><p>[1] thoughts are compiled from <em>Deep work</em> by Cal Newport.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93c133bbf500" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/deep-work-a-scarcity-in-digital-age-93c133bbf500">Deep Work: A Scarcity in Digital Age</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Recover DeepLens Password]]></title>
            <link>https://benjamin-wang.medium.com/recover-deeplens-password-cf46b769ff2d?source=rss-9f912e7eae81------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf46b769ff2d</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[deeplens]]></category>
            <category><![CDATA[ssh]]></category>
            <dc:creator><![CDATA[Benjamin Wang]]></dc:creator>
            <pubDate>Thu, 14 Jun 2018 11:00:46 GMT</pubDate>
            <atom:updated>2021-01-05T12:54:46.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*Fe46jFXoEsabqo-4.png" /><figcaption>From DeepLens website.</figcaption></figure><p>Hey DeepLens fans!</p><p>In case you forgot your SSH password initially set up up for your DeepLens like I did, sad face. Here are a few steps that I compiled from different resources, proven to be working.</p><p><strong>Items to prepare before you proceed:</strong></p><ul><li>usb keyboard</li><li>micro hdmi to hdmi cable</li><li>monitor with hdmi input</li></ul><p><strong>Steps to follow:</strong></p><ol><li>press ESC key until bios screen comes up</li><li>select continue and hit enter</li><li>press ESC once (<strong>important step!</strong>), then select the SECOND option with “recovery mode” at the end</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*0cVB3FIu1u7Br--f.png" /></figure><p>4. select root shell and press enter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*DA2dwSLR7QI25MzK.png" /></figure><p>5. type in the following commands</p><pre>mount -rw -o remount /<br>passwd aws_cam</pre><p>6. follow the prompts to reset the password for that user</p><p>7. press ctrl+d</p><p>8. continue with booting the device or reboot</p><h3>References</h3><p>[1] <a href="https://forums.aws.amazon.com/thread.jspa?messageID=816849&amp;tstart=0">https://forums.aws.amazon.com/thread.jspa?messageID=816849&amp;tstart=0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf46b769ff2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>