<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Flipboard Engineering</title>
        <description>The official Flipboard engineering blog</description>
        <link>http://engineering.flipboard.com</link>
        <atom:link href="http://engineering.flipboard.com/feed.xml" rel="self" type="application/rss+xml" />
        
            <item>
                <title>VAST Video Ad Service</title>
                <author>https://www.linkedin.com/in/guangle-fan-13496731/ (Guangle Fan)</author>
                <description>&lt;p&gt;Videos are more ubiquitous than ever before: there are virtually no boundaries on how, when and where people can interact with video content. Flipboard as a curation platform brings multi-format content to peoples around their personal interests and passions. There has been tremendous opportunity for video ads to perform efficiently on our platform. At Flipboard, we have been building video inventory &lt;!--break--&gt; since 2013 in the form of transcoding, storing, and serving proprietary format video ads on an in-house platform. As we see high-quality beautiful video ads satisfy advertisers, we also face the challenge of scaling the platform to meet the increasing demands of our video ad inventory. To bring Flipboard’s video ad inventory to a larger group of advertisers, we need a programmatic selling channel that supports standard video ad formats, provides easy performance measurement and flexible video behavior control. This is where VAST can help.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
  &lt;div class=&quot;col-sm-3&quot;&gt;&lt;img src=&quot;/assets/vastvideoad/screen_1.png&quot; style=&quot;max-width:100%;&quot; /&gt;&lt;/div&gt;
  &lt;div class=&quot;col-sm-3&quot;&gt;&lt;img src=&quot;/assets/vastvideoad/screen_2.png&quot; style=&quot;max-width:100%;&quot; /&gt;&lt;/div&gt;
  &lt;div class=&quot;col-sm-3&quot;&gt;&lt;img src=&quot;/assets/vastvideoad/vast_demo.gif&quot; style=&quot;max-width:100%;&quot; /&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;h2 id=&quot;what-is-vast-&quot;&gt;What is VAST ?&lt;/h2&gt;
&lt;p&gt;VAST is the Video Ad Serving Template published by &lt;a href=&quot;https://www.iab.com/guidelines/digital-video-ad-serving-template-vast-2-0/&quot;&gt;IAB&lt;/a&gt;. It is a universal XML schema that gives video players information about which ad to play, how the ad should show up, how long it should last, and whether peoples are able to skip it. It’s important because it lets video players and ad servers speak the same language. Before VAST, advertisers had very little information about the publisher’s player implementation. It also allows ad platforms to easily exchange ads with each other. For example, a physical video media file can be hosted at Service A, and passed through a chain of Services B, C, D, and served to consumers on publisher platform E. Each service will be able to wrap the ad with its own event trackers for performance measurement. VAST has been the most adopted video ad standard by advertisers and publishers, and the prevailing version is VAST 2.0.&lt;/p&gt;

&lt;h2 id=&quot;how-do-we-serve-vast-ads-&quot;&gt;How do we serve VAST ads ?&lt;/h2&gt;
&lt;p&gt;At Flipboard, we have ad inventory across our iOS, Android, Samsung Briefing, and Web products. The way some publishers implement a VAST compatible video player on the client side is OK, but not ideal. As a comparison, a backend-centric approach can work better, where a single VAST compliance server handles all the third-party communication, while the client side has consistent behavior across multiple platforms. It’s also easy to check ad quality before serving to the client and optimize package selection logic.
Each transaction of VAST ads involves communication among multiple ad services. Each service provides a unique XML payload which carries its own event trackers including impression/error/click through, user engagement trackers, and a special HTTP URL called VAST tag pointing to its source third-party service, or its parent ad service. The pointers form a virtual network between services involved in the transaction. Crawling pointers along the chain, our ad server can eventually fetch the inline ad with media files. It also organizes all trackers by event types, assembles with media resources, adds our own event trackers, and then sends down a validated ad package to the clients.&lt;/p&gt;

&lt;p&gt;Our internal inventory management tool supports two types of VAST ads. The first type connects to open market ad platforms such as Rubicon and Tremor (with more coming), where we don’t necessarily limit a particular group of buyers. Instead, inventory would be bid on and taken by the winner, although we provide various types of topic-based packages like business, technology, fashion, etc. Geo targeting is also available.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/vastvideoad/third_party_ad.png&quot; style=&quot;max-width:90%;&quot; /&gt;
&lt;/div&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/vastvideoad/ad_network.png&quot; style=&quot;max-width:90%;&quot; /&gt;
&lt;/div&gt;

&lt;p&gt;Another type is through direct sale channel advertisers providing us VAST tags hosted by a third-party server, e.g DCM or their own ad server, where they set up the tag once and distribute to all VAST compatible publisher platforms. This means we don’t need to transcode or host the media content, which lets us hammer out a deal in much faster way with less cost of communication and maintenance.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/vastvideoad/direct_sale_ad.png&quot; style=&quot;max-width:60%;&quot; /&gt;
&lt;/div&gt;

&lt;p&gt;While both types increase our inventory sell-through rate, the former is such a flexible tool that opens a new selling channel, while the latter reinforces our direct selling channel by the unique ease of setting up.&lt;/p&gt;

&lt;h2 id=&quot;some-challenges&quot;&gt;Some Challenges&lt;/h2&gt;
&lt;p&gt;The communication among third-party ad platforms, DSP, and PSP has a pull-based architecture. That means inventory sellers like us need to constantly send PSP requests whenever they’re available, while buyers on the other side of the platform constantly check and buy what is available at the moment. The fill rate is low based on the total number of requests, and that’s the nature of many ad platforms. At our scale, requests per second can sustain at 10K on average. Since we just started selling a few packages on a few ad platforms, the number can only go up while we expand our footprint. Handling the scale in an efficient way is critical to meet high fill rate of our inventory. On the backend, we optimize our HTTP requests with pooling connections, asynchronous non-blocking calls, properly timing out and recycling resources, etc. Thus we control the usage of CPU, network, memory, and other system resources under a reasonable level without adding more hardware.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/vastvideoad/monitor.png&quot; style=&quot;max-width:100%;&quot; /&gt;
&lt;/div&gt;

&lt;p&gt;Since serving VAST ads involve multiple third-party services by design, it comes with a challenge of quickly identifying and responding to ad quality issues. While an ad can be wrapped and exchange hands several times, it’s not surprising how quickly the trace of the original buyer gets lost. In our ad server, we monitor the change of ad quality by ad system, by service domain, and identify typical reasons in real time. While new causes of ad quality problems may still come up, they tend to repeatedly happen afterward. Our ad server traces all VAST tags that lead to a problematic inline ad, samples the bad instance and surfaces it up to the logging system UI. For a bad instance, we are able to get the message of the preliminary reason, and a chain of VAST tags. That is helpful to quickly respond to the issue, limiting the impact.&lt;/p&gt;

&lt;p&gt;Last but not least, as with any type of ads, tracking performance is half of the work. To be VAST compliant, our mobile app calls third-party tracking URLs from different services at the same time when the event happens, as well as our in-house event trackers. At the backend, we leverage the existing data pipeline to aggregate metrics in a structural way by campaign, order, and ad. We provide insights of quartile of video play, expand, collapse, click-through rate, play duration, etc. We also provide dimensional insights about peoples’ geo location and interests.&lt;/p&gt;

&lt;h2 id=&quot;bottom-line&quot;&gt;Bottom Line&lt;/h2&gt;
&lt;p&gt;Although our service can handle high throughput of third-party requests in the low-fill-rate programmatic world, we can still improve it by encouraging bidding activities with better tailored ad packages, and by leveraging our ad selection model and revenue prediction model. That is the next step to do.&lt;/p&gt;

&lt;p&gt;To sum up, we are excited to announce that Flipboard supports VAST ad as a new programmatic selling channel. We think it can bring us a broader group of advertisers, higher quality ads, and better user experience to our beautiful app.&lt;/p&gt;

</description>
                <pubDate>Tue, 30 May 2017 00:00:00 +0000</pubDate>
                <link>http://engineering.flipboard.com//2017/05/vast-video-ad</link>
                <guid isPermaLink="true">http://engineering.flipboard.com//2017/05/vast-video-ad</guid>
            </item>
        
            <item>
                <title>Detecting Trustworthy Domains</title>
                <author>https://www.linkedin.com/in/mikecora/ (Mike Vlad Cora)</author>
                <description>&lt;p&gt;High quality, truthful, diverse and informative content is Flipboard’s #1 priority. Hand-picking trusted sources guarantees quality, but is very time consuming, and can potentially miss out on the multitude of excellent but smaller publishers. To address this problem, we’ve developed a machine learning (ML) system called the &lt;em&gt;Domain Ranker&lt;/em&gt;. Its goal is to automatically distinguish authoritative domains from plagiarists, spammers and other low quality sources. It learns to predict how our editorial team would label a domain by analyzing the content and the signals generated by our users. The &lt;em&gt;Domain Ranker&lt;/em&gt; scales our editorial thinking to a much larger amount of content than we could handle manually, ensuring high quality across all topics.&lt;!--break--&gt;&lt;/p&gt;

&lt;h2 id=&quot;overview&quot;&gt;Overview&lt;/h2&gt;

&lt;p&gt;Flipboard has indexed hundreds of millions of articles in the last year alone. In addition to the constant stream of articles from our trusted partners, any user can add any web article into their personal magazines, further expanding Flipboard’s pool to non-partner publishers.&lt;/p&gt;

&lt;p&gt;Our community support and editorial teams are constantly battling the endless churn of spam sites. Through their efforts, we have identified thousands of labeled spam domains, alongside thousands of partner and whitelisted publishers. The &lt;em&gt;Domain Ranker&lt;/em&gt; is a machine learning system that uses this labeled data to learn and generalize our editorial thinking to unlabeled sources.&lt;/p&gt;

&lt;p&gt;In this blog post I do not delve into the theory behind any of the machine learning classifiers used. They are all well known, off-the-shelf implementations in the &lt;a href=&quot;http://scikit-learn.org/&quot; target=&quot;_blank&quot;&gt;scikit-learn&lt;/a&gt; Python library. Instead I will focus on the engineering journey: managing the live data pipeline, exploring and engineering reasonable features, and experimenting with a multitude of classifiers to maximize accuracy.&lt;/p&gt;

&lt;p&gt;I compare an ML project to an open-ended “Choose Your Own Adventure” book: every path leads to an almost unlimited number of forks, fraught with perils and rewards. There are many paths that end in failure, even more leading to mediocre results, and just a few (if any) that end in happiness &lt;del&gt;ever-after&lt;/del&gt; for a while.&lt;/p&gt;

&lt;h2 id=&quot;choose-your-own-ml-adventure&quot;&gt;Choose Your Own ML Adventure&lt;/h2&gt;

&lt;p&gt;Firstly, we need to consider whether ML is the right solution. Is this adventure worth playing? Can we get by with some manually built (but static) heuristics? Or is a machine learning system that automatically learns heuristics necessary for this problem?&lt;/p&gt;

&lt;p&gt;New domains that publish content are registered daily on the web. Out of the millions of domains whose content users add to their Flipboard magazines, less than 1% have been labeled by our editorial team. There is an endless supply of usage data and content analysis features we can use. It is not clear at all what set of features distinguishes low quality from high quality, especially since spam continuously disguises itself as good content. So the cover of the &lt;em&gt;Domain Ranker&lt;/em&gt; ML adventure book looks interesting enough to crack open.&lt;/p&gt;

&lt;h3 id=&quot;data-pipeline&quot;&gt;Data Pipeline&lt;/h3&gt;

&lt;p&gt;If your data pipeline is anything like ours, it will be distributed through the multiverse, covering the breadth of technologies for good measure: Kafka queues, S3 data stores, HBase, RDS, Redis, and the like. Your ML adventure will be a lot more pleasant if you can collapse the multiverse into one source of truth, ideally a memory-mapped database. Not having to deal with the complexity of a distributed system allows more focus on exploring features and classifiers.&lt;/p&gt;

&lt;p&gt;Luckily for me, Flipboard has a custom written memory-mapped index of important article usage events that is ridiculously fast to access.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/domainranking/data_pipeline.png&quot; style=&quot;max-width:100%;&quot; /&gt;
&lt;/div&gt;

&lt;p&gt;To seed the domain features, I first ran a one-time-job to aggregate all historical article events (views, likes, shares, etc.) into domain-level features, and stored them in the index for quick retrieval and updating. Then a continuous stream of real-time article usage events arrives through various pipes: Kafka queues, S3 file stores, MySQL databases, etc. These usage events are reprocessed into article features and &lt;a href=&quot;http://math.stackexchange.com/questions/106700/incremental-averageing&quot; target=&quot;_blank&quot;&gt;incrementally averaged&lt;/a&gt; into the domain-level features, for all labeled and unlabeled domains.&lt;/p&gt;

&lt;h3 id=&quot;feature-engineering&quot;&gt;Feature Engineering&lt;/h3&gt;

&lt;p&gt;Specialized knowledge about the data space goes a long way towards a successful ML application. In addition to the raw data, it is worth experimenting with more complex polynomial features that may describe a decision boundary. In our case, an obvious place to start was with article features that imply quality and engagement, like &lt;em&gt;clickthrough rate&lt;/em&gt;, &lt;em&gt;article length&lt;/em&gt;, &lt;em&gt;quickbacks&lt;/em&gt;, etc.&lt;/p&gt;

&lt;p&gt;It is important to use features that do not suffer from presentation bias. As an example, users tend to read articles that are higher in a feed as opposed to ones lower in a feed. If a recommender system boosts popular articles, a positive feedback loop occurs: popular articles are ranked higher in the feed, which are more likely to be viewed, further increasing their popularity. So &lt;em&gt;popularity&lt;/em&gt; does not imply quality. Instead, a better feature could be something that measures follow-up actions after the user has read an article (regardless of where in the feed it was).&lt;/p&gt;

&lt;h3 id=&quot;feature-selection&quot;&gt;Feature Selection&lt;/h3&gt;

&lt;p&gt;Another consideration is reducing correlated features. For example, the time spent reading an article may be a useful feature, but it is directly correlated to length. A more informative feature is percentage of &lt;em&gt;quickbacks&lt;/em&gt; for a domain: the portion of views with less than 10% completion. This indicates a bad experience through either pop-up ads, or users quickly realizing the content is low quality.&lt;/p&gt;

&lt;p&gt;Many more features than the ones listed are used in practice. &lt;a href=&quot;https://en.wikipedia.org/wiki/Feature_selection&quot; target=&quot;_blank&quot;&gt;Feature selection&lt;/a&gt; helped to identify correlated and irrelevant features. We ran a fairly exhaustive search over subsets of features and picked ones that gave the best results on our validation set. The search was performed by running various classifiers on subsets of features and comparing the results.&lt;/p&gt;

&lt;h3 id=&quot;feature-scaling&quot;&gt;Feature Scaling&lt;/h3&gt;

&lt;p&gt;Features can have wildly different scales. Article length for instance, ranges from 20 words to thousands of words, while &lt;em&gt;quickbacks&lt;/em&gt; are a percentage. We can simplify the job for the classifiers by scaling all features to be in the same 0 to 1 range. This extra heuristic can also help reduce the impact of outliers. For example, if a user leaves the app open on an article, it may generate an unrealistically large view time.  My rule of thumb for a reasonable scaling range was the feature average +/- 2 times the standard deviation.&lt;/p&gt;

&lt;p&gt;Some classifiers are not affected by different feature scales, while others completely fall apart. In our case, the &lt;a href=&quot;http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html&quot; target=&quot;_blank&quot;&gt;SVC&lt;/a&gt; classifier took an inordinately long time to train on unscaled features compared to other classifiers. Once the features were scaled, training got exponentially faster. Based on many experiments, scaling the features increased training speed and marginally improved the results.&lt;/p&gt;

&lt;h3 id=&quot;model-selection&quot;&gt;Model Selection&lt;/h3&gt;

&lt;p&gt;One can spend a lifetime on this chapter of the adventure. The scikit-learn library makes it quite easy to &lt;a href=&quot;http://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html&quot; target=&quot;_blank&quot;&gt;test many families of classifiers&lt;/a&gt;. Thank you to all of the researchers and grad students who continue supporting this amazing library.&lt;/p&gt;

&lt;p&gt;First we establish a baseline with simple models: &lt;a href=&quot;http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html&quot; target=&quot;_blank&quot;&gt;LogisticRegression&lt;/a&gt;, &lt;a href=&quot;http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html&quot; target=&quot;_blank&quot;&gt;GaussianNB&lt;/a&gt;, &lt;a href=&quot;http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html&quot; target=&quot;_blank&quot;&gt;SVC&lt;/a&gt;, &lt;a href=&quot;http://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html&quot; target=&quot;_blank&quot;&gt;MLPClassifier&lt;/a&gt;. For binary classification, the &lt;a href=&quot;https://en.wikipedia.org/wiki/Receiver_operating_characteristic&quot; target=&quot;_blank&quot;&gt;Receiver Operating Characteristic (ROC) curve&lt;/a&gt; is the guiding light towards success. The goal is to maximize the area under the curve (auc), with a 1 being perfect classification.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/domainranking/dr_baseline.png&quot; style=&quot;max-width:100%;&quot; /&gt;
&lt;/div&gt;

&lt;p&gt;These curves are the average of 5-fold cross validation train/test passes for each classifier, based on this example: &lt;a href=&quot;http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc_crossval.html#sphx-glr-auto-examples-model-selection-plot-roc-crossval-py&quot; target=&quot;_blank&quot;&gt;ROC with cross validation&lt;/a&gt;.&lt;/p&gt;

&lt;h3 id=&quot;ensemble-of-models&quot;&gt;Ensemble of Models&lt;/h3&gt;

&lt;p&gt;Success of the various classifiers is highly dependent on the nature of the features. Armed with the simple models as a baseline, I expanded the search to &lt;a href=&quot;https://en.wikipedia.org/wiki/Ensemble_learning&quot; target=&quot;_blank&quot;&gt;ensembles of models&lt;/a&gt; like &lt;em&gt;&lt;a href=&quot;http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html&quot; target=&quot;_blank&quot;&gt;RandomForest&lt;/a&gt;&lt;/em&gt; and &lt;em&gt;&lt;a href=&quot;http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html&quot; target=&quot;_blank&quot;&gt;GradientBoostingClassifier&lt;/a&gt;&lt;/em&gt;. Additionally, using &lt;a href=&quot;http://rhiever.github.io/tpot/&quot; target=&quot;_blank&quot;&gt;TPOT: your Data Science Assistant&lt;/a&gt;, I was able to squeeze out a bit more prediction accuracy. It uses genetic programming to search for an optimal machine learning pipeline. TPOT resulted in this interesting &lt;em&gt;GradientBoosting&lt;a href=&quot;https://en.wikipedia.org/wiki/Ensemble_learning#Stacking&quot; target=&quot;_blank&quot;&gt;Stack&lt;/a&gt;&lt;/em&gt;, where the results of the &lt;em&gt;&lt;a href=&quot;http://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.html&quot; target=&quot;_blank&quot;&gt;LinearSVC&lt;/a&gt;&lt;/em&gt; and &lt;em&gt;&lt;a href=&quot;http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.BernoulliNB.html&quot; target=&quot;_blank&quot;&gt;BernoulliNB&lt;/a&gt;&lt;/em&gt; classifiers are piped into the &lt;em&gt;GradientBoostingClassifier&lt;/em&gt;:&lt;/p&gt;

&lt;pre style=&quot;overflow:auto; word-wrap: normal; white-space: pre&quot;&gt;
GBoostingStack = make_pipeline(
    make_union(VotingClassifier([(&quot;est&quot;, LinearSVC(C=20.0, 
                                            dual=False,
                                            loss=&quot;squared_hinge&quot;, 
                                            penalty=&quot;l1&quot;))]),
               FunctionTransformer(lambda X: X)),
              
    make_union(VotingClassifier([(&quot;est&quot;, BernoulliNB(alpha=0.001, 
                                            fit_prior=True))]),
               FunctionTransformer(lambda X: X)),
              
    GradientBoostingClassifier(learning_rate=0.1, 
                               max_depth=7, 
                               max_features=0.9, 
                               min_samples_leaf=16, 
                               min_samples_split=2, 
                               subsample=0.95))
&lt;/pre&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/domainranking/dr_ensembles.png&quot; style=&quot;max-width:100%;&quot; /&gt;
&lt;/div&gt;

&lt;p&gt;In addition to the ROC curves and overall accuracy measures, I logged all other usual metrics: &lt;a href=&quot;https://chrisalbon.com/machine-learning/precision_recall_and_F1_scores.html&quot; target=&quot;_blank&quot;&gt;Precision, Recall, F1&lt;/a&gt;, &lt;a href=&quot;https://en.wikipedia.org/wiki/Sensitivity_and_specificity&quot; target=&quot;_blank&quot;&gt;Specificity&lt;/a&gt; and &lt;a href=&quot;https://en.wikipedia.org/wiki/Brier_score&quot; target=&quot;_blank&quot;&gt;Brier Score&lt;/a&gt;. Accuracy is not a sufficient metric, as it is biased by the test data. If accuracy is 90% and the test data is 90% positive, then the classifier may just be labeling the entire data set as positive. &lt;em&gt;Specificity&lt;/em&gt; (true negative rate) is also important, since we are trying to catch and filter out spammers (negative labels).&lt;/p&gt;

&lt;pre style=&quot;overflow:auto; word-wrap: normal; white-space: pre&quot;&gt;
Results           Accuracy |  Precision | Specificity |  Recall |      F1 |   Brier 
-----------------------------------------------------------------------------------
GaussianNB           0.770 |      0.793 |       0.189 |   0.948 |   0.863 |   0.190
SVC                  0.800 |      0.798 |       0.180 |   0.990 |   0.884 |   0.134
MLPClassifier        0.812 |      0.808 |       0.232 |   0.989 |   0.890 |   0.139
LogisticRegression   0.820 |      0.833 |       0.369 |   0.958 |   0.891 |   0.132
RandomForest         0.865 |      0.881 |       0.578 |   0.953 |   0.915 |   0.102
GBoostingStack       0.870 |      0.891 |       0.619 |   0.946 |   0.918 |   0.100
DomainRankStack      0.875 |      0.887 |       0.601 |   0.959 |   0.922 |   0.097
&lt;/pre&gt;

&lt;p&gt;Not all classifiers fail in the same way. Combining the 3 with the highest &lt;em&gt;specificity&lt;/em&gt;, (&lt;em&gt;RandomForest&lt;/em&gt;, &lt;em&gt;GBoostingStack&lt;/em&gt; and &lt;em&gt;LogisticRegression&lt;/em&gt;) into the &lt;em&gt;DomainRankStack&lt;/em&gt; further boosted overall accuracy to a respectably useful 87.5%. Although &lt;em&gt;specificity&lt;/em&gt; is slightly lower than &lt;em&gt;GBoostingStack&lt;/em&gt; alone, the overall &lt;em&gt;F1&lt;/em&gt; and &lt;em&gt;Brier&lt;/em&gt; scores have improved. &lt;em&gt;Brier&lt;/em&gt; score is the mean squared difference between predicted probabilities and the actual outcome, so lower is better. It effectively communicates the confidence of the classifier, in addition to the prediction accuracy.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/domainranking/domainrank_stack.png&quot; style=&quot;max-width:100%;&quot; /&gt;
&lt;/div&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;A “Choose Your Own ML Adventure” never truly ends. It’s a magical book, because on every re-read, new choices may appear, promising more exciting adventures.  Over time, new features may be discovered, or new machine learning models may become available. Spammers may change tactics and find ways to fool a trained system. In production, our models are continuously retrained and verified as new content and data from our users and editorial team is collected.&lt;/p&gt;

&lt;p&gt;A machine learning system is continuously sharpened, never perfected. For this reason, the &lt;em&gt;Domain Ranker&lt;/em&gt; is just one set of “pliers” in our large tool-chest, helping to maintain the high standards of quality, truth and diversity that is expected of Flipboard.&lt;/p&gt;

&lt;h3 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Build and verify the data pipeline first, separately from all else.&lt;/li&gt;
  &lt;li&gt;If possible, aggregate the data on a single machine for much quicker experimentation.&lt;/li&gt;
  &lt;li&gt;Engineer and scale the features.&lt;/li&gt;
  &lt;li&gt;Garbage in/garbage out: be wary of biased and unbalanced training/test data.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;http://scikit-learn.org/&quot; target=&quot;_blank&quot;&gt;scikit-learn&lt;/a&gt; is really fun and incredibly useful.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;http://rhiever.github.io/tpot/&quot; target=&quot;_blank&quot;&gt;TPOT&lt;/a&gt; rocks.&lt;/li&gt;
  &lt;li&gt;Ensembles of classifiers rock.&lt;/li&gt;
  &lt;li&gt;Measure everything, rinse and repeat.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A great guide to practical ML is Martin Zinkevich’s &lt;a href=&quot;http://martin.zinkevich.org/rules_of_ml/rules_of_ml.pdf&quot; target=&quot;_blank&quot;&gt;Best Practices for ML Engineering&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Special thanks to &lt;a href=&quot;http://benfrederickson.com&quot; target=&quot;_blank&quot;&gt;Ben Frederickson&lt;/a&gt;, &lt;a href=&quot;https://www.linkedin.com/in/arnab-bhadury-a6304768&quot; target=&quot;_blank&quot;&gt;Arnab Bhadury&lt;/a&gt;, &lt;a href=&quot;https://www.linkedin.com/in/style/&quot; target=&quot;_blank&quot;&gt;David Creemer&lt;/a&gt;, &lt;a href=&quot;https://twitter.com/miaq&quot; target=&quot;_blank&quot;&gt;Mia Quagliarello&lt;/a&gt; and &lt;a href=&quot;https://twitter.com/Xtel&quot; target=&quot;_blank&quot;&gt;Christel van der Boom&lt;/a&gt; for proofreading.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Enjoyed this post? &lt;a href=&quot;https://about.flipboard.com/careers/&quot; target=&quot;_blank&quot;&gt;We’re hiring!&lt;/a&gt;&lt;/p&gt;
&lt;style type=&quot;text/css&quot;&gt;
      
      .axis path,
      .axis line {
        fill: none;
        stroke: black;
        shape-rendering: crispEdges;
      }
      
      .axis text {
        font-family: sans-serif;
        font-size: 11px;
      }
&lt;/style&gt;

</description>
                <pubDate>Wed, 12 Apr 2017 00:00:00 +0000</pubDate>
                <link>http://engineering.flipboard.com//2017/04/domainranking</link>
                <guid isPermaLink="true">http://engineering.flipboard.com//2017/04/domainranking</guid>
            </item>
        
            <item>
                <title>Clustering Similar Stories Using LDA</title>
                <author>https://www.linkedin.com/in/arnab-bhadury-a6304768 (Arnab Bhadury)</author>
                <description>&lt;p&gt;There is more to a story than meets the eye, and some stories deserve to be presented from more than just one perspective. With Flipboard 4.0, we have released story roundups, a new feature that adds coverage from multiple sources to a story and provides you with a fuller picture of an event. &lt;!--break--&gt;&lt;/p&gt;

&lt;p&gt;Here’s how it looks:&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/storyclustering/storycluster.gif&quot; style=&quot;max-width:50%;&quot; /&gt;
&lt;/div&gt;

&lt;p&gt;With our scale of millions of articles and constant stream of documents, it’s impossible to generate these roundups manually. So, we have developed a clustering algorithm that’s both fast and scalable, and in this blog post, I will explain how we create these roundups on Flipboard.&lt;/p&gt;

&lt;h2 id=&quot;why-is-this-difficult&quot;&gt;Why is this difficult?&lt;/h2&gt;

&lt;p&gt;Although there are many sophisticated automatic clustering algorithms, such as &lt;a href=&quot;https://en.wikipedia.org/wiki/K-means_clustering&quot;&gt;K-means&lt;/a&gt; or &lt;a href=&quot;https://en.wikipedia.org/wiki/Hierarchical_clustering&quot;&gt;Agglomerative clustering&lt;/a&gt;, story clustering is a non-trivial problem. Because each text document can contain any word from our vocabulary, most text document representations are extremely high-dimensional. In high-dimensional spaces, even basic clustering or similarity measures fail or are very slow.&lt;/p&gt;

&lt;p&gt;Additionally, two very similar documents often have very different word usages. For example, one article may use the term &lt;em&gt;kitten&lt;/em&gt; and another may use &lt;em&gt;feline&lt;/em&gt;, but both articles could be referring to the same &lt;em&gt;cat&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Furthermore, we don’t know the number of roundups that we expect to see beforehand. This makes it difficult for us to directly use parameteric algorithms such as K-means. Our clustering algorithm also needs to be fast and easy to update, because there is a constant stream of documents coming into our system.&lt;/p&gt;

&lt;h2 id=&quot;overview&quot;&gt;Overview&lt;/h2&gt;

&lt;p&gt;Since even the most basic distance measures fail in high dimensions, the first thing we do is lower the problem’s dimensionality. We represent each of our text documents as a &lt;a href=&quot;https://en.wikipedia.org/wiki/Bag-of-words_model&quot;&gt;bag-of-words&lt;/a&gt;, and remove stop-words and rare words from our vocabulary. Even after an aggressive trimming, the documents are still very high-dimensional. We then we use &lt;a href=&quot;https://www.cs.princeton.edu/~blei/papers/BleiNgJordan2003.pdf&quot;&gt;Latent Dirichlet Allocation&lt;/a&gt; (LDA) to further lower the documents’ dimensionality. We use LDA because this algorithm is amenable for text modeling and provides us with interpretable lower dimensional representations of documents.&lt;/p&gt;

&lt;p&gt;LDA is generally used for &lt;a href=&quot;http://psiexp.ss.uci.edu/research/papers/sciencetopics.pdf&quot;&gt;qualitative understanding&lt;/a&gt; of big text corpora. The &lt;em&gt;latent&lt;/em&gt; topics that the model learns are highly interpretable and provide deep insights to the data. However, that’s not the only thing it can be used for; it is also a very logical algorithm to use for dimensionality reduction as it learns a mapping of sparse document-term vectors to sparse document-topic vectors in an unsupervised setting.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/storyclustering/docfactors.gif&quot; style=&quot;max-width:100%;&quot; /&gt;
&lt;/div&gt;

&lt;p&gt;Once the documents are represented over a tractable number of dimensions, all similarity and distance measures come into play. For our story clustering, we simply map all the documents to this conceptual level (latent topics), and look at the neighbours for each document within a certain distance. We use an approximate &lt;a href=&quot;https://en.wikipedia.org/wiki/Nearest_neighbor_search&quot;&gt;nearest neighbour&lt;/a&gt; model because it only requires us to look at a small neighbourhood of documents to generate these clusters.&lt;/p&gt;

&lt;p&gt;The following sections explain how we use LDA for this problem, and then introduce some tricks to optimize LDA using Alias tables and Metropolis-Hastings tests.&lt;/p&gt;

&lt;h2 id=&quot;high-level-overview-of-lda&quot;&gt;High-level overview of LDA&lt;/h2&gt;

&lt;p&gt;LDA is a probabilistic &lt;a href=&quot;https://en.wikipedia.org/wiki/Generative_model&quot;&gt;generative model&lt;/a&gt; that extracts the thematic structure in a big document collection. The model assumes that every topic is a distribution of words in the vocabulary, and every document (described over the same vocabulary) is a distribution of a small subset of these topics. This is a statistical way to say that each topic (e.g. &lt;em&gt;space&lt;/em&gt;) has some representative words (&lt;em&gt;star&lt;/em&gt;, &lt;em&gt;planet&lt;/em&gt;, etc.), and each document is only about a handful of these topics.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/storyclustering/lda.png&quot; style=&quot;max-width:100%;&quot; /&gt;
&lt;/div&gt;

&lt;p&gt;For example, let’s assume that we have a few topics as shown in the figure above. Knowing these topics, when we see a document explaining &lt;em&gt;Detecting and classifying pets using deep learning&lt;/em&gt;, we can confidently say that the document is mostly about &lt;em&gt;Topic 2&lt;/em&gt; and a little about &lt;em&gt;Topic 1&lt;/em&gt; but not at all about &lt;em&gt;Topic 3&lt;/em&gt; and &lt;em&gt;Topic 4&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;LDA automatically infers these topics given a large collection of documents and expresses those (and future) documents in terms of topics instead of raw terms. The key advantage of doing this is that we allow term variability as the document is represented at a higher conceptual (topic) level rather than at the raw word level. This is akin to many success stories in image classification tasks using deep learning, where the classification is done on a higher conceptual level instead of on the pixel level.&lt;/p&gt;

&lt;p&gt;To infer the above &lt;em&gt;latent&lt;/em&gt; topics, we do posterior inference on the model using Gibbs Sampling. What it essentially comes down to is to estimate the &lt;em&gt;best&lt;/em&gt; topic for each word seen in every document. This is estimated by:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;p (Z_{d,n} = k) \propto (C_k^d + \alpha) \times\frac{C_k^w + \beta}{C_k + V\beta}&lt;/script&gt;

&lt;p&gt;where &lt;script type=&quot;math/tex&quot;&gt;w&lt;/script&gt; is the word seen in the &lt;script type=&quot;math/tex&quot;&gt;n&lt;/script&gt;th position in document &lt;script type=&quot;math/tex&quot;&gt;d&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;C_k^d&lt;/script&gt; is the number of times the topic &lt;script type=&quot;math/tex&quot;&gt;k&lt;/script&gt; has appeared in document &lt;script type=&quot;math/tex&quot;&gt;d&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;C_k^w&lt;/script&gt; is the number of times the word &lt;script type=&quot;math/tex&quot;&gt;w&lt;/script&gt; has been estimated with topic &lt;script type=&quot;math/tex&quot;&gt;k&lt;/script&gt; in the whole corpus, and &lt;script type=&quot;math/tex&quot;&gt;C_k&lt;/script&gt; is the number of times the topic &lt;script type=&quot;math/tex&quot;&gt;k&lt;/script&gt; has been assigned in the corpus. It is a sensible equation which suggests that a topic is more likely to be assigned if it has been assigned to other words in the same document or when the term has been assigned to that same topic several times in the whole document corpus.&lt;/p&gt;

&lt;p&gt;We calculate the above equation for each topic and define a &lt;a href=&quot;https://en.wikipedia.org/wiki/Multinomial_distribution&quot;&gt;multinomial distribution&lt;/a&gt; (a weighted dice roll), and generate a random topic from that distribution. The code for LDA’s inference (CGS-LDA) looks like this:&lt;/p&gt;

&lt;style&gt;
.smallrow {
  width: 100% !important;
}
  pre {
    word-wrap: normal;
    word-break: normal;
  }
&lt;/style&gt;

&lt;div class=&quot;language-c highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
2
3
4
5
6
7
8
9
10
11
12
13
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]);&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;decrement_count_matrices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;CDK&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;CWK&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;CK&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;multinomial_distribution&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;increment_count_matrices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
  &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This computation can be very expensive if we try to capture more than a thousand topics, because the algorithmic complexity becomes &lt;script type=&quot;math/tex&quot;&gt;O(DNK)&lt;/script&gt; per iteration. What we would ideally like is to get rid of &lt;script type=&quot;math/tex&quot;&gt;O(K)&lt;/script&gt; loop for each word in a document.&lt;/p&gt;

&lt;h2 id=&quot;optimizing-lda-using-alias-tables-and-metropolis-hastings-tests&quot;&gt;Optimizing LDA using Alias Tables and Metropolis-Hastings Tests&lt;/h2&gt;

&lt;p&gt;Fortunately, there has been a lot of new research (&lt;a href=&quot;https://arxiv.org/pdf/1412.1576v1&quot;&gt;LightLDA&lt;/a&gt;, &lt;a href=&quot;http://www.sravi.org/pubs/fastlda-kdd2014.pdf&quot;&gt;AliasLDA&lt;/a&gt;) to speed up the sampling process and reduce the computational complexity to &lt;script type=&quot;math/tex&quot;&gt;O(DN)&lt;/script&gt;. The key question here is: Is it really possible to generate a single sample from a weighted multinomial distribution in under &lt;script type=&quot;math/tex&quot;&gt;O(K)&lt;/script&gt; time?&lt;/p&gt;

&lt;p&gt;The answer, not surprisingly, is “no” because generating a &lt;script type=&quot;math/tex&quot;&gt;K&lt;/script&gt; dimensional multinomial probability array &lt;script type=&quot;math/tex&quot;&gt;p&lt;/script&gt; takes at least &lt;script type=&quot;math/tex&quot;&gt;O(K)&lt;/script&gt; time because we need to know the weight for each index. But once this array is created, generating a sample is simply a matter of generating a random number from &lt;script type=&quot;math/tex&quot;&gt;[0, sum(p)]&lt;/script&gt; and checking which index of the array the number falls in. And if we needed more samples from the same distribution, all future samples would only require &lt;script type=&quot;math/tex&quot;&gt;O(1)&lt;/script&gt; time.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/storyclustering/prob_vector.gif&quot; style=&quot;max-width:100%;&quot; /&gt;
&lt;/div&gt;

&lt;p&gt;Instead of taking a single sample each time from the distribution, if we take &lt;script type=&quot;math/tex&quot;&gt;K&lt;/script&gt; samples each time the table is generated, then the amortized sampling complexity would be &lt;script type=&quot;math/tex&quot;&gt;O(1)&lt;/script&gt;. But this method has huge memory implications because the sizes of these arrays are dependent on the sum of the weights, and in LDA’s case, they can get extremely massive due to dependencies on count matrices (&lt;script type=&quot;math/tex&quot;&gt;C_d^k&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;C_k^w&lt;/script&gt; and &lt;script type=&quot;math/tex&quot;&gt;C_k&lt;/script&gt;).&lt;/p&gt;

&lt;h3 id=&quot;alias-sampling&quot;&gt;Alias Sampling&lt;/h3&gt;

&lt;p&gt;Walker’s &lt;a href=&quot;https://en.wikipedia.org/wiki/Alias_method&quot;&gt;Alias method&lt;/a&gt; is an effective way to compactly store these probability vectors (Space complexity: &lt;script type=&quot;math/tex&quot;&gt;O(K)&lt;/script&gt;), 
while keeping the sampling complexity at &lt;script type=&quot;math/tex&quot;&gt;O(1)&lt;/script&gt;.  Instead of defining a long row vector, Alias sampling defines a completely filled 2-dimensional
table (dim: &lt;script type=&quot;math/tex&quot;&gt;K \times 2)&lt;/script&gt; from which its easy to sample from in constant time.&lt;/p&gt;

&lt;p&gt;These tables are generated by first multiplying each element by &lt;script type=&quot;math/tex&quot;&gt;K&lt;/script&gt;, followed by a Robin Hood
algorithm and maintaining two lists: &lt;em&gt;rich&lt;/em&gt; and &lt;em&gt;poor&lt;/em&gt;. &lt;em&gt;rich&lt;/em&gt; contains all the elements that have
a greater weight than &lt;script type=&quot;math/tex&quot;&gt;1.0&lt;/script&gt;, and the &lt;em&gt;poor&lt;/em&gt; stores the rest. This is followed by a simple
iteration of putting the poor elements in the table cell first, and then filling up the height if
needed by “stealing” from the rich:&lt;/p&gt;

&lt;div id=&quot;aliastable&quot;&gt;&lt;/div&gt;

&lt;div style=&quot;text-align:center&quot;&gt;&lt;div style=&quot;display:inline-block;&quot;&gt;
&lt;button type=&quot;button&quot; class=&quot;btn btn-default&quot; id=&quot;randomize_aliastable&quot;&gt;
  &lt;span class=&quot;glyphicon glyphicon-refresh&quot;&gt;&lt;/span&gt; Randomize Probabilities
&lt;/button&gt;
&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Each column has a height of 1.0 with a maximum of two different array indices. For sample generation, a random number is generated between &lt;script type=&quot;math/tex&quot;&gt;[0, len(table)]&lt;/script&gt; to pick the column, and then we generate a random floating point between &lt;script type=&quot;math/tex&quot;&gt;[0, 1.0]&lt;/script&gt; and see which region the decimal number falls in.&lt;/p&gt;

&lt;h3 id=&quot;metropolis-hastings-algorithm--test&quot;&gt;Metropolis Hastings Algorithm / Test&lt;/h3&gt;

&lt;p&gt;Coming back to our LDA case, every time we need to sample a topic for a word in a document, we could generate &lt;script type=&quot;math/tex&quot;&gt;K&lt;/script&gt; samples. However, that would be wrong because the update equation is dependent on the count matrices, and stale samples don’t represent the &lt;strong&gt;true&lt;/strong&gt; probability distribution of the inference.&lt;/p&gt;

&lt;p&gt;Here’s where &lt;a href=&quot;https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm&quot;&gt;Metropolis-Hastings&lt;/a&gt; (MH) algorithm comes into play. MH algorithm is a &lt;a href=&quot;https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo&quot;&gt;Markov-Chain Monte Carlo&lt;/a&gt; (MCMC) method to move around the probability space with the intention of converging to an objective. Given an objective function &lt;script type=&quot;math/tex&quot;&gt;O(\cdot)&lt;/script&gt;, a proposal function &lt;script type=&quot;math/tex&quot;&gt;P(\cdot)&lt;/script&gt; and a proposed position in the probability space, MH algorithm acts as a guide telling the algorithm whether it is a good or bad idea to move from the current position &lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt; to the proposed point &lt;script type=&quot;math/tex&quot;&gt;x'&lt;/script&gt;. The acceptance of a new proposed position is computed by:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;A(x' | x) = min(1, \frac{O(x')}{O(x)}\frac{P(x | x')}{P (x' | x)})&lt;/script&gt;

&lt;p&gt;If the algorithm thinks that it’s a great idea to move, MH will always accept the proposal.&lt;/p&gt;

&lt;p&gt;The following toy example shows how we can approximate the area of a random function with Metropolis-Hastings sampling. In this example, we try to approximate the shape of a complicated non-linear function and use a standard Gaussian distribution (&lt;script type=&quot;math/tex&quot;&gt;\mathcal{N}(0, 1)&lt;/script&gt;) multiplied with a step-size to generate proposals.&lt;/p&gt;

&lt;script src=&quot;https://d3js.org/d3.v4.min.js&quot;&gt;&lt;/script&gt;

&lt;div id=&quot;mh_vis&quot; style=&quot;text-align:center;&quot;&gt;&lt;/div&gt;
&lt;div id=&quot;mh_vis_text&quot; style=&quot;text-align:center;&quot;&gt;&lt;/div&gt;
&lt;div id=&quot;mh_vis_stepsize&quot; style=&quot;text-align:center;&quot;&gt;&lt;/div&gt;
&lt;div id=&quot;mh_vis_slider&quot; style=&quot;text-align:center;&quot;&gt;
&lt;input id=&quot;mh_vis_s&quot; type=&quot;range&quot; min=&quot;0.1&quot; max=&quot;0.9&quot; step=&quot;0.1&quot; value=&quot;0.3&quot; oninput=&quot;updateStepsize(value)&quot; list=&quot;stepsizes&quot; style=&quot;text-align:center;&quot; /&gt;
&lt;datalist id=&quot;stepsizes&quot;&gt;
  &lt;option&gt;0.1&lt;/option&gt;
  &lt;option&gt;0.3&lt;/option&gt;
  &lt;option&gt;0.5&lt;/option&gt;
  &lt;option&gt;0.7&lt;/option&gt;
  &lt;option&gt;0.9&lt;/option&gt;
&lt;/datalist&gt;
&lt;/div&gt;
&lt;script src=&quot;/assets/storyclustering/mh.js&quot;&gt;&lt;/script&gt;

&lt;script src=&quot;/assets/storyclustering/alias_table.js&quot;&gt;&lt;/script&gt;

&lt;script&gt;
var table = new AliasTable([0.4, 0.3, 0.2, 0.08, 0.02]);
table.displayState(d3.select(&quot;#aliastable&quot;), 0);
function randomizeAliasTable() {
    table.stop = true;
    table = new AliasTable([Math.random(), Math.random(), Math.random(), Math.random(), Math.random()]);
    table.displayState(d3.select(&quot;#aliastable&quot;), 0);
}
d3.select(&quot;#randomize_aliastable&quot;).on(&quot;click&quot;, randomizeAliasTable);
&lt;/script&gt;

&lt;p&gt;From the above example, it can be seen that proposal functions control the convergence speed of the algorithm. In the ideal scenario, we would like a high-acceptance rate and the ability to move quickly around the space. For the toy example above, step-sizes of &lt;script type=&quot;math/tex&quot;&gt;0.2 - 0.4&lt;/script&gt; achieve the best results.&lt;/p&gt;

&lt;h3 id=&quot;back-to-lda&quot;&gt;Back to LDA&lt;/h3&gt;

&lt;p&gt;We would like to have high proposal acceptance rates, good space coverage, and simple proposal generation complexity. LightLDA authors suggest using the expressions within the LDA’s update equation as proposal functions. These expressions match the function in certain regions. This has two further advantages: we don’t need to compute anything extra and simply use the statistics (count matrices) that we would have collected anyway, and we don’t actually need to create alias tables for one of the proposals.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;p (Z_{d,n} = k) \propto (\underbrace{C_k^d + \alpha}_{doc-proposal}) \times \underbrace{(\frac{C_k^w + \beta}{C_k + V\beta}}_{term-proposal})&lt;/script&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;Z_d&lt;/script&gt; acts as a proxy alias table for the doc-proposal because it stores the number of times each topic has appeared in the document &lt;script type=&quot;math/tex&quot;&gt;d&lt;/script&gt;, and if we generate a random number between &lt;script type=&quot;math/tex&quot;&gt;[0, len(d)]&lt;/script&gt;, we get a sample from the doc-proposal. For the word-proposals, we generate alias tables for each word and use the afforementioned Alias Sampling trick.&lt;/p&gt;

&lt;p&gt;We cycle between these two proposals, and do the MH test on the fly, and accept/reject the proposals. We recompute an alias table for a word every time we have used &lt;script type=&quot;math/tex&quot;&gt;K&lt;/script&gt; proposals. The acceptance probabilities for doc-proposal (&lt;script type=&quot;math/tex&quot;&gt;A_d&lt;/script&gt;) and word-proposal (&lt;script type=&quot;math/tex&quot;&gt;A_w&lt;/script&gt;) given a proposal topic &lt;script type=&quot;math/tex&quot;&gt;p&lt;/script&gt; and the current topic &lt;script type=&quot;math/tex&quot;&gt;k&lt;/script&gt; can be calculated by using the LDA’s update equation as the objective function, and the doc and word proposals as the proposal functions.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;A_d = min\{ 1, \underbrace{\frac{(C_p^d + \alpha) (C_p^w + \beta) (C_k + V\beta)} {(C_k^d + \alpha) (C_k^w + \beta) (C_p + V\beta)}}_{objective} \times \underbrace{\frac{(C_k^d + \alpha)} {(C_p^d + \alpha)} \}}_{doc-proposal}&lt;/script&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;A_w = min \{ 1, \underbrace{\frac{(C_p^d + \alpha) (C_p^w + \beta) (C_k + V\beta)} {(C_k^d + \alpha) (C_k^w + \beta) (C_p + V\beta)}}_{objective} \times \underbrace{\frac{(C_k^w + \beta) (C_p + V\beta)} {(C_p^w + \beta) (C_k + V\beta)}}_{term-proposal} \}&lt;/script&gt;

&lt;p&gt;Using Alias tables and MH tests, the algorithm looks like the following:&lt;/p&gt;

&lt;div class=&quot;language-cpp highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]);&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;proposal&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;coinflip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;decrement_count_matrices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;proposal&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;c1&quot;&gt;// doc-proposal
&lt;/span&gt;      &lt;span class=&quot;n&quot;&gt;index&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randomInt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]));&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;];&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;mh_acceptance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;compute_doc_acceptance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;c1&quot;&gt;// term-proposal
&lt;/span&gt;      &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alias_sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;mh_acceptance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;compute_term_acceptance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// MH-test
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mh_sample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;randomFloat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mh_sample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mh_acceptance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;increment_count_matrices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// reject proposal, revert to k
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;increment_count_matrices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// accept proposal
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;	
  &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;By doing this, the algorithmic complexity of LDA comes down to an amortized &lt;script type=&quot;math/tex&quot;&gt;O(DN)&lt;/script&gt; which allows us to process documents an order of magnitude faster. The following table and the graph compare the runtime (in seconds) of LDA of 60,000 documents after 100 iterations (convergence) on a single process.&lt;/p&gt;

&lt;center&gt;
&lt;table align=&quot;center&quot;&gt;
  &lt;col width=&quot;160&quot; /&gt;
  &lt;col width=&quot;90&quot; /&gt;
  &lt;col width=&quot;90&quot; /&gt;
  &lt;col width=&quot;90&quot; /&gt;
  &lt;col width=&quot;90&quot; /&gt;
  &lt;col width=&quot;90&quot; /&gt;
    &lt;tr&gt;
      &lt;th&gt;    Num. of Topics    &lt;/th&gt;
      &lt;th&gt; 100 &lt;/th&gt;
      &lt;th&gt; 200 &lt;/th&gt;
      &lt;th&gt; 300 &lt;/th&gt;
      &lt;th&gt; 500 &lt;/th&gt;
      &lt;th&gt; 1000 &lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt; CGS LDA &lt;/td&gt;
      &lt;td&gt; 3427.99 &lt;/td&gt;
      &lt;td&gt; 7605.02 &lt;/td&gt;
      &lt;td&gt; 12190.54 &lt;/td&gt;
      &lt;td&gt; 25274.20 &lt;/td&gt;
      &lt;td&gt; 57492.22 &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt; MH/Alias LDA &lt;/td&gt;
      &lt;td&gt; 601.06 &lt;/td&gt;
      &lt;td&gt; 616.07 &lt;/td&gt;
      &lt;td&gt; 620.82 &lt;/td&gt;
      &lt;td&gt; 646.38 &lt;/td&gt;
      &lt;td&gt; 685.19 &lt;/td&gt;
    &lt;/tr&gt;
  &lt;/table&gt;
&lt;/center&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/storyclustering/comparison.png&quot; style=&quot;max-width:100%;&quot; /&gt;
&lt;/div&gt;

&lt;h2 id=&quot;clustering&quot;&gt;Clustering&lt;/h2&gt;

&lt;p&gt;LDA provides us with a sparse and robust representation of texts that reduces term variability in much lower dimensions. In 1000 or lower dimensions, most simple algorithms work really well. When each document is represented in this space, we do a fast &lt;a href=&quot;http://en.wikipedia.org/wiki/Nearest_neighbor_search#Approximate_nearest_neighbor&quot;&gt;Approximate Nearest Neighbour search&lt;/a&gt;, and cluster all documents that are within a certain distance from each other.&lt;/p&gt;

&lt;p&gt;Using a distance based metric has an added advantage of being able to capture near and exact duplicates. The documents that are mapped too close to each other (purple circle) are considered to be the same story. The documents that are a certain radius away from the exact duplicates (pink circle) make up the roundups for each story.&lt;/p&gt;

&lt;div id=&quot;cluster_vis&quot; style=&quot;text-align:center;&quot;&gt;&lt;/div&gt;
&lt;script src=&quot;/assets/storyclustering/clustering.js&quot;&gt;&lt;/script&gt;

&lt;p&gt;Removing exact duplicates helps in capturing different views on an event, and here is an example of one of our story-clusters where the roundups capture differing perspectives on the same news.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/storyclustering/griezmann.gif&quot; style=&quot;max-width:50%;&quot; /&gt;
&lt;/div&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Story roundups directly help us in diversifying our users’ feeds while also providing users with multiple perspectives on important stories. We had a lot of fun implementing this cool new feature, not least because we came across several new tricks that can be applied in multiple domains.&lt;/p&gt;

&lt;p&gt;Alias Sampling and MH algorithm have been around for a long time but they are only now being used in tandem to optimize posterior and predictive inference problems.&lt;/p&gt;

&lt;h3 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;LDA is awesome not just in context of qualitative topic analysis but also in terms of dimensionality reduction.&lt;/li&gt;
  &lt;li&gt;Simple algorithms work really well in low dimensions; (almost) everything fails in very high dimensions.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Bayesian Machine Learning doesn’t have to be slow or expensive.&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;If you made it this far, I hope you learned a new way to optimize some posterior inference problems - Alias Tables and MH tests are an amazing combination.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Extra special thanks to &lt;a href=&quot;http://benfrederickson.com&quot;&gt;Ben Frederickson&lt;/a&gt; for suggestions, edits and
the Alias Table visualization. Thanks to &lt;a href=&quot;http://www.linkedin.com/in/sizzler&quot;&gt;Dale Cieslak&lt;/a&gt;, &lt;a href=&quot;https://www.linkedin.com/in/mikecora&quot;&gt;Mike Vlad Cora&lt;/a&gt; and &lt;a href=&quot;https://twitter.com/miaq&quot;&gt;Mia Quagliarello&lt;/a&gt; for proofreading.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Enjoyed this post? &lt;a href=&quot;https://about.flipboard.com/careers/&quot;&gt;We’re hiring!&lt;/a&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML&quot;&gt;
&lt;/script&gt;&lt;/p&gt;

&lt;style type=&quot;text/css&quot;&gt;
      
      .axis path,
      .axis line {
        fill: none;
        stroke: black;
        shape-rendering: crispEdges;
      }
      
      .axis text {
        font-family: sans-serif;
        font-size: 11px;
      }
&lt;/style&gt;

</description>
                <pubDate>Wed, 08 Feb 2017 00:00:00 +0000</pubDate>
                <link>http://engineering.flipboard.com//2017/02/storyclustering</link>
                <guid isPermaLink="true">http://engineering.flipboard.com//2017/02/storyclustering</guid>
            </item>
        
            <item>
                <title>iOS Meetup</title>
                <author>https://twitter.com/timonus (Tim Johnsen)</author>
                <description>&lt;p&gt;Flipboard was honored to host a meetup of the &lt;a href=&quot;http://www.meetup.com/Palo-Alto-iOS-Developers/events/224782782/&quot;&gt;Palo Alto iOS Developers&lt;/a&gt; group about developing apps for watchOS 2 at our office in Palo Alto last week. &lt;a href=&quot;https://twitter.com/benmorrow&quot;&gt;Ben Morrow&lt;/a&gt;, writer of the &lt;a href=&quot;http://www.happy.watch/&quot;&gt;Happy Watch&lt;/a&gt; blog and host of several Apple Watch hackathons, gave a talk deep diving into various aspects of watchOS 2.
&lt;!--break--&gt;&lt;/p&gt;

&lt;center&gt;&lt;a href=&quot;http://www.meetup.com/Palo-Alto-iOS-Developers/photos/26382293/#441587485&quot;&gt;&lt;img src=&quot;/assets/ios-meetup/1.jpg&quot; style=&quot;width:100%; max-width:658px;&quot; /&gt;&lt;/a&gt;&lt;/center&gt;

&lt;p&gt;We also gave a short talk sharing a bit of the story about how we built our WatchKit app and what we’ve got in store for watchOS 2.&lt;/p&gt;

&lt;center&gt;&lt;blockquote class=&quot;instagram-media&quot; data-instgrm-version=&quot;4&quot; style=&quot; background:#FFF; border:0; border-radius:3px; box-shadow:0 0 1px 0 rgba(0,0,0,0.5),0 1px 10px 0 rgba(0,0,0,0.15); margin: 1px; max-width:658px; padding:0; width:99.375%; width:-webkit-calc(100% - 2px); width:calc(100% - 2px);&quot;&gt;&lt;div style=&quot;padding:8px;&quot;&gt; &lt;div style=&quot; background:#F8F8F8; line-height:0; margin-top:40px; padding:50.0% 0; text-align:center; width:100%;&quot;&gt; &lt;div style=&quot; background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAsCAMAAAApWqozAAAAGFBMVEUiIiI9PT0eHh4gIB4hIBkcHBwcHBwcHBydr+JQAAAACHRSTlMABA4YHyQsM5jtaMwAAADfSURBVDjL7ZVBEgMhCAQBAf//42xcNbpAqakcM0ftUmFAAIBE81IqBJdS3lS6zs3bIpB9WED3YYXFPmHRfT8sgyrCP1x8uEUxLMzNWElFOYCV6mHWWwMzdPEKHlhLw7NWJqkHc4uIZphavDzA2JPzUDsBZziNae2S6owH8xPmX8G7zzgKEOPUoYHvGz1TBCxMkd3kwNVbU0gKHkx+iZILf77IofhrY1nYFnB/lQPb79drWOyJVa/DAvg9B/rLB4cC+Nqgdz/TvBbBnr6GBReqn/nRmDgaQEej7WhonozjF+Y2I/fZou/qAAAAAElFTkSuQmCC); display:block; height:44px; margin:0 auto -44px; position:relative; top:-22px; width:44px;&quot;&gt;&lt;/div&gt;&lt;/div&gt;&lt;p style=&quot; color:#c9c8cd; font-family:Arial,sans-serif; font-size:14px; line-height:17px; margin-bottom:0; margin-top:8px; overflow:hidden; padding:8px 0 7px; text-align:center; text-overflow:ellipsis; white-space:nowrap;&quot;&gt;&lt;a href=&quot;https://instagram.com/p/7LbSIjm8J_/&quot; style=&quot; color:#c9c8cd; font-family:Arial,sans-serif; font-size:14px; font-style:normal; font-weight:normal; line-height:17px; text-decoration:none;&quot; target=&quot;_top&quot;&gt;A photo posted by Flipboard (@flipboard)&lt;/a&gt; on &lt;time style=&quot; font-family:Arial,sans-serif; font-size:14px; line-height:17px;&quot; datetime=&quot;2015-09-03T18:29:20+00:00&quot;&gt;Sep 3, 2015 at 11:29am PDT&lt;/time&gt;&lt;/p&gt;&lt;/div&gt;&lt;/blockquote&gt;
&lt;script async=&quot;&quot; defer=&quot;&quot; src=&quot;//platform.instagram.com/en_US/embeds.js&quot;&gt;&lt;/script&gt;&lt;/center&gt;

&lt;p&gt;We’d like to thank &lt;a href=&quot;https://twitter.com/msuprovici&quot;&gt;Mike Suprovici&lt;/a&gt; and the community for giving us the oppourtunity to host this event.&lt;/p&gt;

&lt;p&gt;Here’s a complete video of the meetup&lt;/p&gt;

&lt;center&gt;&lt;iframe width=&quot;640&quot; height=&quot;360&quot; src=&quot;https://www.youtube.com/embed/hfvSY238i4Q?rel=0&quot; frameborder=&quot;0&quot; allowfullscreen=&quot;&quot; style=&quot;max-width:640px; width:100%;&quot;&gt;&lt;/iframe&gt;&lt;/center&gt;

&lt;p&gt;P.S. &lt;a href=&quot;https://about.flipboard.com/careers/&quot;&gt;We’re hiring!&lt;/a&gt;&lt;/p&gt;
</description>
                <pubDate>Wed, 09 Sep 2015 00:00:00 +0000</pubDate>
                <link>http://engineering.flipboard.com//2015/09/ios-meetup</link>
                <guid isPermaLink="true">http://engineering.flipboard.com//2015/09/ios-meetup</guid>
            </item>
        
            <item>
                <title>Introducing PSync</title>
                <author>https://github.com/hzsweers (Zac Sweers)</author>
                <description>&lt;p&gt;Here on the Android team at Flipboard, we have a lot of settings for users to adjust their experience. If you throw in internal settings, we have about 100 total preferences to manage. This is &lt;em&gt;a lot&lt;/em&gt; of boilerplate to maintain, because preferences in Android have no built-in synchronization (unlike Resources). Our &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;PreferenceFragment&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; class has a couple hundred lines of boilerplate fields at the top where we keep in-code mirrors to these preference values. This design is tedious, brittle, and requires a lot of overhead to keep in sync with XML. We developed a Gradle plugin called PSync to solve this problem.
&lt;!--break--&gt;&lt;/p&gt;

&lt;p&gt;PSync is an Android-specific Gradle plugin that generates Java representations of XML preferences. These Java classes can then be used directly in your code. The generated code is very much inspired by how &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;R.java&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; works for resources, and should feel familiar to developers. It’s easy to use, has some simple configurations for fine-tuning your generated code, and is ready to drop into both library and application projects.&lt;/p&gt;

&lt;p&gt;A full overview can be found on the &lt;a href=&quot;https://github.com/Flipboard/psync&quot;&gt;GitHub README&lt;/a&gt;, but here’s a quick preview:&lt;/p&gt;

&lt;p&gt;Say you have a preference:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
2
3
4
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;&amp;lt;CheckboxPreference
    android:key=&quot;show_images&quot;
    android:defaultValue=&quot;true&quot;
    /&amp;gt;
&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;You can reference it like this:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
2
3
4
5
6
7
8
9
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;String theKey = P.showImages.key;
boolean current = P.showImages.get();
P.showImages.put(false).apply();

// If you use Rx-Preferences
P.showImages.rx().asObservable().omgDoRxStuff!

// If you need it
boolean theDefault = P.showImages.defaultValue();
&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The generated Java code looks like so:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;public final class P {
    public static final class showImages {
        public static final String key = &quot;show_images&quot;;

        public static final boolean defaultValue() {
            return true;
        }

        public static final boolean get() {
            return PREFERENCES.getBoolean(key, defaultValue());
        }

        public static final SharedPreferences.Editor put(final boolean val) {
            return PREFERENCES.edit().putBoolean(key, val);
        }

        public static final Preference&amp;lt;Boolean&amp;gt; rx() {
            return RX_SHARED_PREFERENCES.getBoolean(key);
        }
    }
}
&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;It’s robust, fully tested, and should be ready for use with standard XML preferences. The process of writing tests for a plugin like PSync is worth its own blog post or talk, so look forward to that coming up. Future plans for this project include adding support for mixing in your own non-XML preferences, and supporting the full range of the SharedPreferences API.&lt;/p&gt;

&lt;p&gt;We hope you find it useful, and welcome contributions and feedback on the repo: &lt;a href=&quot;https://github.com/Flipboard/psync&quot;&gt;https://github.com/Flipboard/psync&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you like open source and working on cool projects, we are looking for talented Android engineers to join our team here in Palo Alto, California! &lt;a href=&quot;http://hire.jobvite.com/m?31pnnhwW&quot;&gt;Apply here&lt;/a&gt;&lt;/p&gt;
</description>
                <pubDate>Tue, 08 Sep 2015 00:00:00 +0000</pubDate>
                <link>http://engineering.flipboard.com//2015/09/psync</link>
                <guid isPermaLink="true">http://engineering.flipboard.com//2015/09/psync</guid>
            </item>
        
            <item>
                <title>Presenting BottomSheet</title>
                <author>https://github.com/emilsjolander (Emil Sjölander)</author>
                <description>&lt;p&gt;We are happy to introduce &lt;a href=&quot;http://github.com/flipboard/bottomsheet&quot;&gt;BottomSheet&lt;/a&gt; a new Open Source Android UI Component!&lt;/p&gt;

&lt;p&gt;At Flipboard, we love building visually stunning and highly interactive UIs. When building these UIs, we tend to build them as fairly stand alone components. This makes it very easy for our developers to implement a similar interaction model and aesthetic across the whole product while working in parallel. BottomSheet is a UI component we developed to facilitate a new interaction model for saving an article to one of your magazines (otherwise known as “The Flip UI”).
&lt;!--break--&gt;&lt;/p&gt;

&lt;p&gt;The result of our efforts is a design you can now see in the current version of Flipboard.&lt;/p&gt;

&lt;center&gt;
    &lt;div class=&quot;row&quot;&gt;
        &lt;img src=&quot;/assets/bottomsheet/flipui.gif&quot; style=&quot;max-width:95%;&quot; /&gt;
    &lt;/div&gt;
&lt;/center&gt;

&lt;p&gt;BottomSheet fits perfectly with Google’s Material Design aesthetic as well, matching their Bottom Sheet &lt;a href=&quot;http://www.google.com/design/spec/components/bottom-sheets.html&quot;&gt;specification&lt;/a&gt;. We think this component is great for displaying many types of views, from a simple intent picker to something as complex as the example shown from Flipboard. In its simplest form, BottomSheet can be used to show any view in a sort of modal UI that’s presented from the bottom of the screen can be interactively dismissed. At Flipboard, we think it’s very important that things feel responsive, and having interactive animations is an important part of this.&lt;/p&gt;

&lt;p&gt;Apart from providing a component for presenting views in a BottomSheet, we have also have a module for common views developers might like to present in a BottomSheet. The first such component we’re releasing is the &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;IntentPickerSheetView&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;. This sheet view is initialized with an intent and will show a grid of activities that can handle the intent. It works very similarly to Android’s built in IntentChooser, and looks very similar to the picker used in Lollipop and above. There are a couple of ways in which our implementation improves upon the system intent chooser:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;It can be interactively dismissed, making it feel much more responsive.&lt;/li&gt;
  &lt;li&gt;It adds an easy-to-use API for filtering and sorting the activities shown. Ever wanted to filter out the Bluetooth activity when adding sharing functionality to your app? With the &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;IntentPickerSheetView&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;, that’s simple!&lt;/li&gt;
&lt;/ul&gt;

&lt;center&gt;
    &lt;div class=&quot;row&quot;&gt;
        &lt;img src=&quot;/assets/bottomsheet/intentpicker.gif&quot; style=&quot;max-width:95%;&quot; /&gt;
    &lt;/div&gt;
&lt;/center&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;IntentPickerSheetView intentPickerSheet = new IntentPickerSheetView(MainActivity.this, shareIntent, &quot;Share with...&quot;, new IntentPickerSheetView.OnIntentPickedListener() {
    @Override
    public void onIntentPicked(Intent intent) {
        bottomSheet.dismissSheet();
        startActivity(intent);
    }
});
// Filter out built in sharing options such as bluetooth and beam.
intentPickerSheet.setFilter(new IntentPickerSheetView.Filter() {
    @Override
    public boolean include(IntentPickerSheetView.ActvityInfo info) {
        return !info.componentName.getPackageName().startsWith(&quot;com.android&quot;);
    }
});
// Sort activities in reverse order for no good reason
intentPickerSheet.setSortMethod(new Comparator&amp;lt;IntentPickerSheetView.ActvityInfo&amp;gt;() {
    @Override
    public int compare(IntentPickerSheetView.ActvityInfo lhs, IntentPickerSheetView.ActvityInfo rhs) {
        return rhs.label.compareTo(lhs.label);
    }
});
bottomSheet.showWithSheetView(intentPickerSheet);
&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We would love for you to join us on &lt;a href=&quot;http://github.com/flipboard/bottomsheet&quot;&gt;GitHub&lt;/a&gt; to collaborate in adding many more of these common components!&lt;/p&gt;

&lt;p&gt;And before I send you off to scour the interwebs for cat GIFs to display in your new BottomSheets, I want to take this opportunity to advertise that we are looking for talented Android engineers to join our team here in Palo Alto, California. &lt;a href=&quot;http://hire.jobvite.com/m?31pnnhwW&quot;&gt;Apply here&lt;/a&gt;&lt;/p&gt;

</description>
                <pubDate>Thu, 04 Jun 2015 00:00:00 +0000</pubDate>
                <link>http://engineering.flipboard.com//2015/06/bottomsheet</link>
                <guid isPermaLink="true">http://engineering.flipboard.com//2015/06/bottomsheet</guid>
            </item>
        
            <item>
                <title>Image Scaling using Deep Convolutional Neural Networks</title>
                <author>https://twitter.com/normantasfi (Norman Tasfi)</author>
                <description>&lt;style&gt;
    h4 {
      box-sizing: border-box;
      color: rgb(85, 85, 85);
      display: block;
      font-family: HelveticaNeue-Thin, 'Helvetica Neue', 'Segoe UI', Arial, sans-serif;
      font-size: 18px;
      font-weight: 200;
      height: 20px;
      line-height: 20px;
      margin-bottom: 10px;
      margin-left: auto;
      margin-right: auto;
      margin-top: 40px;
      max-width: 640px;
      width: 640px;
    }
&lt;/style&gt;

&lt;p class=&quot;deck&quot;&gt;
This past summer I interned at Flipboard in Palo Alto, California. I worked on machine learning based problems, one of which was Image Upscaling. This post will show some preliminary results, discuss our model and its possible applications to Flipboard’s products&lt;!--break--&gt;.
&lt;/p&gt;

&lt;p&gt;High quality and a print-like finish play a key role in Flipboard’s design language. We want users to enjoy a consistent and beautiful experience throughout all of Flipboard’s content, as if they had a custom print magazine in hand. Providing this experience consistently is difficult. Different factors, such as image quality, deeply affect the overall quality of the presented content. Image quality varies greatly depending on the image’s source. This varying image quality is especially apparent in magazines that display images across the whole page in a full bleed format.&lt;/p&gt;

&lt;p&gt;When we display images on either the web or mobile devices they must be above a certain threshold to display well. If we receive a large image on our web product we can create breathtaking full bleed sections.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/convnets/good.png&quot; /&gt;
    &lt;div class=&quot;caption&quot;&gt;
    Full bleed High Quality Image
    &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Lower resolution images introduce pixelation, over smoothing and artifacts when scaled above 100%. This is especially apparent in a full bleed presentation as seen below. This severely reduces the quality of presentation in our products.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/convnets/bad.png&quot; /&gt;
    &lt;div class=&quot;caption&quot;&gt;
    Full bleed Low Quality Image
    &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;What is the cause of this? In general, when we need an image of size X that is required to be of size Y it must be run through a scaling algorithm. This algorithm performs a mathematical operation to scale the image pixels to the desired size Y.  Some of the possible algorithms are bicubic, bilinear, and nearest-neighbor interpolation. Many of the algorithms listed above perform an interpolation between pixel values to create a transition. These algorithms use the surrounding pixels to guess what the missing values should be in the new image. The problem in the case of scaling the image to a larger size is when there are too many ‘new’ values to be filled in the image. These algorithms try to make “guesses” of what the new values should be but this introduces errors in the process which leads to noise, haloing, and artifacts.&lt;/p&gt;

&lt;p&gt;Before we go any further I would like to give a high level introduction to both the traditional and convolutional flavours of Neural Networks. If you have a good grasp of them feel free to skip ahead to next section. Following the introduction to Neural Networks there is a preliminary results section, discussion of the model architectures, design decisions, and applications.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: Smaller nuances of Neural Networks will not be covered in the introduction.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;neuralNetworks&quot; href=&quot;#neuralNetworks&quot; class=&quot;anchor-link&quot;&gt;
    Neural Networks
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;Neural Networks are an amazing type model that is able to learn from given data. They have a large breadth of applications and have enjoyed a recent resurgence in popularity in many domains such as computer vision, audio recognition, and natural language processing. Some recent feats include &lt;a href=&quot;http://googleresearch.blogspot.ca/2014/11/a-picture-is-worth-thousand-coherent.html&quot;&gt;captioning images&lt;/a&gt;, &lt;a href=&quot;http://www.forbes.com/sites/paulrodgers/2015/02/28/googles-deepmind-masters-atari-games/&quot;&gt;playing Atari&lt;/a&gt;, &lt;a href=&quot;http://blogs.nvidia.com/blog/2015/02/24/deep-learning-drive/&quot;&gt;aiding self-driving cars&lt;/a&gt;, and &lt;a href=&quot;http://104.131.78.120/&quot;&gt;language translation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Neural Networks exist in different configurations, such as &lt;a href=&quot;http://en.wikipedia.org/wiki/Convolutional_neural_network&quot;&gt;convolutional&lt;/a&gt; and &lt;a href=&quot;http://en.wikipedia.org/wiki/Recurrent_neural_network&quot;&gt;recurrent&lt;/a&gt;, that are each good at different types of tasks. Learning ‘modes’ also exist: supervised and unsupervised; we will only focus on supervised learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Supervised learning&lt;/strong&gt; is described as a network that is trained on both an input and an output. This ‘mode’ is used to predict new outputs given an input. An example of this would be training a network on thousands of pictures of cats and dogs which have been manually labelled and then asking, on a new picture, is this a cat or dog?&lt;/p&gt;

&lt;p&gt;On a structural level a Neural Network is a feedforward graph where each of the nodes, known as units, performs a nonlinear operation on the incoming inputs. Each of the inputs has a weight that the network is able to learn through an algorithm known as backpropagation.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/convnets/basic_nn.png&quot; /&gt;
    &lt;div class=&quot;caption&quot;&gt;
    Basic Neural Network
    &lt;br /&gt;
    Source: &lt;a href=&quot;http://en.wikipedia.org/wiki/Artificial_neural_network#/media/File:Colored_neural_network.svg&quot;&gt;Wikipedia&lt;/a&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The structure of a Neural Network is flexible and based on the task at hand. We are free to customize our network by selecting attributes such as: the number of hidden layers (blue nodes above), number of units per layer, number of connections per unit etc. These attributes known as hyperparameters describe our model’s structure and behaviour. Selecting these parameters correctly is critical to achieving high performance. Hyperparameters are usually chosen through random &lt;a href=&quot;http://en.wikipedia.org/wiki/Hyperparameter_optimization#Grid_search&quot;&gt;grid search&lt;/a&gt;, optimization algorithms (&lt;a href=&quot;http://en.wikipedia.org/wiki/Bayesian_optimization&quot;&gt;bayesian&lt;/a&gt; and &lt;a href=&quot;http://scipy-lectures.github.io/advanced/mathematical_optimization/&quot;&gt;gradient based&lt;/a&gt;), or simple trial and error.&lt;/p&gt;

&lt;p&gt;As mentioned previously the units within a network perform a mathematical operation on the inputs. We can take a closer look by calculating a simple numerical example involving a single unit with a handful of inputs.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/convnets/our_simple_nn.png&quot; /&gt;
    &lt;div class=&quot;caption&quot;&gt;
    Our simple model
    &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The unit above takes three inputs: &lt;script type=&quot;math/tex&quot;&gt;\displaystyle x_1, x_2, x_3&lt;/script&gt; and a scalar bias term &lt;script type=&quot;math/tex&quot;&gt;\displaystyle b&lt;/script&gt; (not shown). Each of these inputs has weightings that are referred to as &lt;script type=&quot;math/tex&quot;&gt;\displaystyle w_1, w_2,&lt;/script&gt; and &lt;script type=&quot;math/tex&quot;&gt;\displaystyle  w_3&lt;/script&gt;. The weights express the importance of the incoming input. The bias term allows us to offset our weighted value to the left or right. For this example we will use the &lt;strong&gt;Rectified Linear (ReL)&lt;/strong&gt; function as the units mathematical operation, more formally known as an &lt;strong&gt;activation function&lt;/strong&gt;, expressed as:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\displaystyle \begin{array}{ll}
f(x) = \begin{cases}
x &amp; {\text{if}}\ x&gt;0 \\
0 &amp; {\text{if}}\ otherwise \\ 
\end{cases}
\end{array} %]]&gt;&lt;/script&gt;

&lt;p&gt;The gist of this activation function is any input value below zero is considered as zero and anything above remains the same. It has an output range of &lt;script type=&quot;math/tex&quot;&gt;\displaystyle [0, \infty]&lt;/script&gt;. Other activation functions can also be used such as the &lt;a href=&quot;http://en.wikipedia.org/wiki/Sigmoid_function&quot;&gt;sigmoid&lt;/a&gt;, &lt;a href=&quot;http://mathworld.wolfram.com/HyperbolicTangent.html&quot;&gt;hyperbolic tangent&lt;/a&gt;, and &lt;a href=&quot;http://arxiv.org/abs/1302.4389&quot;&gt;maxout&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;So how do we calculate an output value? To do so we need to compute &lt;script type=&quot;math/tex&quot;&gt;\displaystyle f(W^Tx+b)&lt;/script&gt;. The first step is to compute the vector product between transpose &lt;script type=&quot;math/tex&quot;&gt;\displaystyle W&lt;/script&gt; and &lt;script type=&quot;math/tex&quot;&gt;\displaystyle x,&lt;/script&gt; defined as &lt;script type=&quot;math/tex&quot;&gt;\displaystyle W^Tx&lt;/script&gt;. Our bias value is then added to this result before finally being passed through our activation function.&lt;/p&gt;

&lt;p&gt;To make this example a little more concrete we will use some random numbers. Say we have the following vectors corresponding to our weights, inputs, and scalar bias value:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\displaystyle W = [1, 0.2, 0.1] \\ x =[0.74, 5, 8] \\ b=1.0&lt;/script&gt;

&lt;p&gt;Going step by step we calculate the result of &lt;script type=&quot;math/tex&quot;&gt;\displaystyle W^Tx&lt;/script&gt;:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\displaystyle 1.0(0.74)+0.2(5.0)+0.1(8.0)=2.54&lt;/script&gt;

&lt;p&gt;Then our bias value is added &lt;script type=&quot;math/tex&quot;&gt;\displaystyle W^Tx + b&lt;/script&gt;:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\displaystyle 2.54+1.0 = 3.54&lt;/script&gt;

&lt;p&gt;We then take this quantity and pass it through our activation function &lt;script type=&quot;math/tex&quot;&gt;\displaystyle f(x)&lt;/script&gt;:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\displaystyle f(3.54) = 3.54&lt;/script&gt;

&lt;p&gt;As per our function definition we see that if x is greater than zero we will get the value of x out, which in this case is 3.54.&lt;/p&gt;

&lt;p&gt;Why is this exciting? Well, in terms of a single unit, it is not too exciting. As it stands, we can tweak the weights and bias value to model only the most basic of functions. Our little example lacks ‘expressive power’. In order to increase our ‘expressive power’ we can chain and link units together to form larger networks as seen below.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/convnets/our_complex_nn.png&quot; /&gt;
    &lt;div class=&quot;caption&quot;&gt;
        Our bigger network
    &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;The equations for the network above, where &lt;script type=&quot;math/tex&quot;&gt;\displaystyle W_{from,to}&lt;/script&gt; is the weight from one unit to another, is as follows:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\displaystyle \begin{array}{ll}
z_1 = f(W_{l1,h1}^T x + b) \\
z_2 = f(W_{l1,h2}^T x + b) \\
y = f(W_{h12,o1}^T z + b)
\end{array}&lt;/script&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\displaystyle z_1&lt;/script&gt; is the the same expression we calculated earlier! See how we have chained them together to create a more complicated network? We are applying the same calculation over and over. We use the output from a previous layer of units to compute the next. The values are propagated through the network until they arrive at the final layer. We call this process &lt;strong&gt;forward propagation&lt;/strong&gt;. But this process is of little use to us if we need to change the output of our network as it makes no adjustments to the weights and biases.&lt;/p&gt;

&lt;p&gt;To update the weights and biases of our network we will use an algorithm known as &lt;strong&gt;backpropagation&lt;/strong&gt;. We will focus on a supervised approach where our network is given pairs of data: input x and the desired output y. In order to use &lt;strong&gt;backpropagation&lt;/strong&gt; in this supervised manner we need to quantify our network’s performance. We must define an &lt;strong&gt;error&lt;/strong&gt; that compares the result of forward propagation through our network, &lt;script type=&quot;math/tex&quot;&gt;\displaystyle \hat{y}&lt;/script&gt;(our estimated value), against the desired value &lt;script type=&quot;math/tex&quot;&gt;\displaystyle y&lt;/script&gt;.&lt;/p&gt;

&lt;p&gt;This comparison between values is formally known as a &lt;strong&gt;cost function&lt;/strong&gt;. It can be defined however you want but for this post we will use the mean squared error function:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\displaystyle E_{MSE}(x,y) = \displaystyle\frac{1}{n} \vert \hat{y}(x) - y \vert ^ 2&lt;/script&gt;

&lt;p&gt;This function gives us a magnitude of error. If our network was given randomly initialized weights and biases the output will be far from the desired y value, causing a large output from &lt;script type=&quot;math/tex&quot;&gt;\displaystyle E_{MSE}&lt;/script&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Backpropagation&lt;/strong&gt; takes this magnitude and propagates it from the back of the network to the front adjusting the weights and biases along the way. The amount of adjustment to each weight and bias can be thought of as its contribution to the error and is calculated through &lt;a href=&quot;http://en.wikipedia.org/wiki/Gradient_descent&quot;&gt;gradient descent&lt;/a&gt;. This algorithm seeks to minimize the error function above by changing the weights and biases.&lt;/p&gt;

&lt;p&gt;The general process to train a Neural Network, given an input vector x and the expected output y, is as follows:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Perform a step of forward propagation through the network with input vector x. We will calculate an output &lt;script type=&quot;math/tex&quot;&gt;\displaystyle \hat{y}&lt;/script&gt;.&lt;/li&gt;
  &lt;li&gt;Calculate the error with our error function. &lt;script type=&quot;math/tex&quot;&gt;\displaystyle E_{MSE}(x,y) = \displaystyle\frac{1}{n} \vert \hat{y}(x) - y \vert ^ 2&lt;/script&gt;.&lt;/li&gt;
  &lt;li&gt;Backpropagate the errors through our network updating the weights and biases.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The above steps are repeated over and over with different xand y pairs until the weights and biases of our network give us the minimum error possible! We are minimizing the &lt;script type=&quot;math/tex&quot;&gt;\displaystyle E_{MSE}&lt;/script&gt; function.&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;convNeuralNetworks&quot; href=&quot;#convNeuralNetworks&quot; class=&quot;anchor-link&quot;&gt;
    Convolutional Neural Networks
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;If you have been paying attention to recent tech articles you will most likely have heard of Neural Networks breaking the state-of-the-art in several domains. These breakthroughs are due in a small part to convolutional Neural Networks.&lt;/p&gt;

&lt;p&gt;Convolutional Neural Networks (convnets) are a slightly different flavour of the typical feed-forward Neural Network. Convnets take some biological inspiration from the visual cortex, which contains small regions of cells that are sensitive to subregions of the visual field. This is referred to as a receptive field. We can mimic this small subfield by learning weights in the form of matrices, referred to as ‘kernels’; which, like their biologically inspired counterparts, are sensitive to similar subregions of an image. We now require a way to express the similarity between our kernel and the subregion. Since the convolution operation essentially returns a measure of ‘similarity’ between two signals we can happily pass a learned kernel, along with a subregion of the image, through this operation and have a measure of similarity returned back!&lt;/p&gt;

&lt;p&gt;Below is an animation of a kernel, in yellow, being convolved over an image, in green, with the result of the operation on the right in red.&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/convnets/Convolution_schematic.gif&quot; /&gt;
    &lt;div class=&quot;caption&quot;&gt;
    Animation of the Convolution Operation.
    &lt;br /&gt;
Source: &lt;a href=&quot;http://deeplearning.stanford.edu/wiki/index.php/Feature_extraction_using_convolution&quot;&gt;Feature extraction using convolution&lt;/a&gt; from Stanford Deep Learning
    &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;To illustrate this let’s run a very simple square kernel which detects directional edges over an image. The weights of our kernel:&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\displaystyle \left( \begin{array}{lll}
-5 &amp; 0 &amp; 0\\
0 &amp; 0 &amp; 0\\
0 &amp; 0 &amp; 5\\
\end{array}\right) %]]&gt;&lt;/script&gt;

&lt;p&gt;Applying the convolutional operation using our kernel, several times over the left image, we get the image on the right:&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/convnets/conv_output.jpg&quot; /&gt;
    &lt;div class=&quot;caption&quot;&gt;
    Animation of the Convolution Operation.
    &lt;br /&gt;
    Source: &lt;a href=&quot;http://www.catenary.com/howto/diagedge.html&quot;&gt;Edge Detection with Matrix Convolution&lt;/a&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;So why is this useful? In the context of Neural Networks several reasons exist:&lt;/p&gt;

&lt;p&gt;This allows us to extract information from the right image above. The kernels inform us of the presence and location of directional edges. When used in a Neural Network we can learn the appropriate weight settings of the kernels to extract out basic features such as edges, gradients and blurs. If the network is deep with enough convolutional layers it will start learning feature combinations off of the previous layers. The simple building blocks of edges, gradients, and blurs become things like eyes, noses, and hair in later layers!&lt;/p&gt;

&lt;div class=&quot;row&quot; style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/convnets/yann_filters.png&quot; /&gt;
    &lt;div class=&quot;caption&quot;&gt;
    Kernels building high level representations from earlier layers. 
    &lt;br /&gt;
    Source: &lt;a href=&quot;http://www.cs.nyu.edu/~yann/talks/lecun-ranzato-icml2013.pdf&quot;&gt;Yann Lecun “ICML 2013 tutorial on Deep Learning”&lt;/a&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Traditionally if we wanted to do work in the image or audio domains we would have to perform feature generation using other algorithms that would preprocess our data into a usable form. This would then allow our machine learning algorithm of choice to make sense of the incoming data. This process is tedious and fragile. By applying a convolutional frontend to our networks we are able to let the algorithm, with minimal preprocessing of the data on our side, to create the features that work best for that specific domain and situation. The network does feature extraction on its own. The learned features of the network work better than most of the algorithmically and hand engineered features.&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;scalingCNN&quot; href=&quot;#scalingCNN&quot; class=&quot;anchor-link&quot;&gt;
    Image Scaling using Convolutional Neural Networks
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;Below is a collection of preliminary results that were produced from the model. The left image is the original ‘high’ resolution. This is the ground truth and what we would hope to get with perfect reconstruction. We scale this original down by a factor of 2x and send it through either a bicubic scaling algorithm or the model. The results are in the center and right positions respectively.&lt;/p&gt;

&lt;div class=&quot;row&quot; id=&quot;imagerow&quot; style=&quot;width: 100%; text-align:center; margin:0px;&quot;&gt;
    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/human_orig.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Original
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/human_bicubic.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Bicubic
        &lt;/div&gt;        
    &lt;/div&gt;

    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/human_model.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Model
        &lt;/div&gt;        
    &lt;/div&gt; 
&lt;/div&gt;

&lt;p&gt;The major differences can be seen between the hairline, eyebrows, and skin on the cheek and forehead.&lt;/p&gt;

&lt;div class=&quot;row&quot; id=&quot;imagerow&quot; style=&quot;width: 100%; text-align:center; margin:0px;&quot;&gt;
    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/building_orig.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Original
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/building_bicubic.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Bicubic  
        &lt;/div&gt;        
    &lt;/div&gt;

    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/building_model.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Model
        &lt;/div&gt;        
    &lt;/div&gt; 
&lt;/div&gt;

&lt;p&gt;The model does a good job along the hard edges on the balcony and on the sun tanning beds in the foreground.&lt;/p&gt;

&lt;div class=&quot;row&quot; id=&quot;imagerow&quot; style=&quot;width: 100%; text-align:center; margin:0px;&quot;&gt;
    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/puppy_orig.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Original
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/puppy_bicubic.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Bicubic 
        &lt;/div&gt;        
    &lt;/div&gt;

    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/puppy_model.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Model
        &lt;/div&gt;        
    &lt;/div&gt; 
&lt;/div&gt;

&lt;p&gt;This one is difficult to see at first glance. The finer details, such as the hair along the side of the ear and on the inside of the ear are present in the model.&lt;/p&gt;

&lt;div class=&quot;row&quot; id=&quot;imagerow&quot; style=&quot;width: 100%; text-align:center; margin:0px;&quot;&gt;
    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/lenna_orig.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Original
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/lenna_bicubic.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Bicubic
        &lt;/div&gt;        
    &lt;/div&gt;

    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/lenna_model.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Model
        &lt;/div&gt;        
    &lt;/div&gt; 
&lt;/div&gt;

&lt;p&gt;No image related work is complete unless Lenna is included in some way. Observe the sharpness of the feathers, noise, lips, and eyes. The pattern on the hat also shows up better in the model output.&lt;/p&gt;

&lt;div class=&quot;row&quot; id=&quot;imagerow&quot; style=&quot;width: 100%; text-align:center; margin:0px;&quot;&gt;
    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/forest_orig.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Original
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/forest_bicubic.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Bicubic
        &lt;/div&gt;        
    &lt;/div&gt;

    &lt;div class=&quot;col-md-4&quot;&gt;
        &lt;img class=&quot;img-responsive&quot; src=&quot;/assets/convnets/results/forest_model.jpg&quot; /&gt;
        &lt;div class=&quot;caption&quot; style=&quot;font-size: 14px&quot;&gt;
            Model
        &lt;/div&gt;        
    &lt;/div&gt; 
&lt;/div&gt;

&lt;p&gt;The major differences between the versions are the tree leaves, shadow shapes and tree textures.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;architecture&quot; href=&quot;#architecture&quot; class=&quot;anchor-link&quot;&gt;
    Architecture
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;Below is one of the architectures used, the primary goal is to double the number of pixels taken in from the image. The architecture is a 8 layer Neural Network composed of three convolutional layers, each shown as stacked pinkish blocks, and four fully connected layers colored in blue. Each layer uses the rectified linear activation function. There is a final dense layer with linear Gaussian units which is not shown below.&lt;/p&gt;

&lt;div style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/convnets/architecture.png&quot; /&gt;
&lt;/div&gt;

&lt;p&gt;A small section of the input image is ingested through the first convolutional layer. This image was collected from the larger image using a square sliding window. The first convolutional contains the largest number of filter maps. The outputs are ‘reprojected’ into a higher dimensionality through the first two dense fully-connected layers. Their output is further processed by the next two convolutional layers. Features from the two convolutional layers are then fed into a series of fully-connected layers. The final output image is calculated by a linear Gaussian layer.&lt;/p&gt;

&lt;p&gt;No pooling operations are used after any of the convolutional layers. While pooling is useful for classification tasks, where invariance to input is important, the location of features detected by each kernel is important. Pooling also discards too much useful information which is the opposite of what is needed for this use case.&lt;/p&gt;

&lt;p&gt;The weights were all initialized using the &lt;a href=&quot;http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf&quot;&gt;Xavier initialization suggested by Glorot &amp;amp; Benigo&lt;/a&gt; and was then slightly tweaked during hyperparameter optimzation. This is defined as &lt;script type=&quot;math/tex&quot;&gt;\displaystyle \frac{ 2 }{n_{in} + n_{out}}&lt;/script&gt; and was sampled from a normal distribution. The biases were all initialized to zero.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;dataset&quot; href=&quot;#dataset&quot; class=&quot;anchor-link&quot;&gt;
    Dataset
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;The network was trained on a large dataset of approximately 3 million samples. The dataset images used natural images including those of animals and outdoor scenes. Some images needed to be filtered out of this set as they included illustrations of animals or text. As each image was of varying size and quality a constraint in the form of a pixel count was added to focus on images which contained a total pixel count of 640,000 and up.&lt;/p&gt;

&lt;p&gt;Each sample within the dataset is a low and high resolution image pair. The low resolution image,  the ‘x’ input, was created by downscaling a high resolution image by a certain factor. While the desired output, ‘y’, was of the original high resolution image. Very mild noise and distortions were added to the input data. The data was normalized to have zero mean by calculating the global mean and to unit variance by dividing through by the standard deviation of the dataset.&lt;/p&gt;

&lt;p&gt;The dataset was divided into subsets of training, testing, and validation; following a 80%, 10%,  and 10% split respectively.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;regularization&quot; href=&quot;#regularization&quot; class=&quot;anchor-link&quot;&gt;
    Regularization
  &lt;/a&gt;
&lt;/h3&gt;

&lt;h4&gt;
  &lt;a name=&quot;maxNorm&quot; href=&quot;#maxNorm&quot; class=&quot;anchor-link&quot;&gt;
    Max Norm
  &lt;/a&gt;
&lt;/h4&gt;
&lt;p&gt;Max norm constraints enforce an absolute upper bound on the weight vectors magnitude for every unit in that layer which stops the network’s weights from ‘exploding’ if the gradient update is too large. Max norm constraints are used in all layers except the final linear Gaussian layer. An aggressive magnitude was used in all of the convolutional layers while the other layers’ magnitudes were much more lax.&lt;/p&gt;

&lt;h4&gt;
  &lt;a name=&quot;L2&quot; href=&quot;#L2&quot; class=&quot;anchor-link&quot;&gt;
    L2
  &lt;/a&gt;
&lt;/h4&gt;
&lt;p&gt;L2 regularization penalizes the network for using large weight vectors, &lt;script type=&quot;math/tex&quot;&gt;\displaystyle W&lt;/script&gt;. This is set by the parameter &lt;script type=&quot;math/tex&quot;&gt;\displaystyle \lambda&lt;/script&gt; and is known as the regularization strength. It is added to the cost function as the term &lt;script type=&quot;math/tex&quot;&gt;\displaystyle \frac{1}{2}\lambda W^2&lt;/script&gt;. The optimization algorithm tries to keep the weights small while minimizing the cost function as before. The convolutional layers and first two densely connected layers have mild regularization applied and the other densely connected layers use a stronger value.&lt;/p&gt;

&lt;h4&gt;
  &lt;a name=&quot;dropout&quot; href=&quot;#droput&quot; class=&quot;anchor-link&quot;&gt;
    Dropout
  &lt;/a&gt;
&lt;/h4&gt;
&lt;p&gt;&lt;a href=&quot;http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf&quot;&gt;Dropout&lt;/a&gt; randomly ‘drops’ units from a layer on each training step, creating ‘sub-architectures’ within the model. It can be viewed as a type of sampling of a smaller network within a larger network. Only the weights of the included units are updated, which makes sure the network does not become too reliant on a few units. This process of removing units happens over and over between runs, so the units being included change. The convolutional layers all have a high inclusion probability of almost 1.0 while the last two fully connected layers include about half the units.&lt;/p&gt;

&lt;div style=&quot;text-align: center&quot;&gt;
    &lt;img src=&quot;/assets/convnets/dropout.png&quot; /&gt;
&lt;/div&gt;

&lt;h3&gt;
  &lt;a name=&quot;training&quot; href=&quot;#training&quot; class=&quot;anchor-link&quot;&gt;
    Training
  &lt;/a&gt;
&lt;/h3&gt;
&lt;p&gt;The model was trained using Stochastic Gradient descent in batch sizes of 250 over the entire training set for ~250 epochs. A highish batchsize was used to smooth out the updates and make better use of the GPUs while still getting some benefit from perturbations of smaller batches.&lt;/p&gt;

&lt;p&gt;The network is trained to minimize a mean square error function. A learning rate scale was used on all weights and biases. The formula for the weights (per layer) was &lt;script type=&quot;math/tex&quot;&gt;\displaystyle 1 - \frac{1}{2} \frac{ n_i }{n_{total}}^2&lt;/script&gt; where &lt;script type=&quot;math/tex&quot;&gt;\displaystyle n_i&lt;/script&gt; is the current layer position and &lt;script type=&quot;math/tex&quot;&gt;\displaystyle n_{total}&lt;/script&gt; is the total number of layers. This scaled the learning rate which helped the earlier layers converge. All the biases had a learning rate multiplier of 2.0. Nesterov momentum was used with an initial value of 0.15 and increased to 0.7 over 45 epochs.&lt;/p&gt;

&lt;p&gt;Amazon g2.2xlarge EC2 instances were used to train the network with &lt;a href=&quot;https://developer.nvidia.com/cuDNN&quot;&gt;NVIDIA’s cuDNN&lt;/a&gt; library added in to speed up training. Training the final model took approximately 19 hours.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;hyperparameters&quot; href=&quot;#hyperparameters&quot; class=&quot;anchor-link&quot;&gt;
    Hyperparameters
  &lt;/a&gt;
&lt;/h3&gt;
&lt;p&gt;The majority of the hyperparameters were selected using an inhouse hyperparameter optimization library that works over clusters of Amazon g2.2xlarge instances. This was performed using a portion of the training dataset and the validation dataset. The process took roughly ~4 weeks and evaluated ~500 different configurations.&lt;/p&gt;

&lt;h4&gt;
  &lt;a name=&quot;variations&quot; href=&quot;#variations&quot; class=&quot;anchor-link&quot;&gt;
    Variations
  &lt;/a&gt;
&lt;/h4&gt;
&lt;p&gt;Some things that did not work out well while working on this problem:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Used a larger batch size of 1000, this worked well, but ran up against local minima quickly. The jitter provided by a smaller batch was useful to bounce out of these minimas.&lt;/li&gt;
  &lt;li&gt;Used a small convolutional network, this was alright but did not generalize as well as the larger convolutional network.&lt;/li&gt;
  &lt;li&gt;Tried to use the weight initialization formula suggested by He et al. : &lt;script type=&quot;math/tex&quot;&gt;\displaystyle \frac{2}{n}&lt;/script&gt;. Unfortunately this caused the network to sputter around and it failed to learn. Might be this specific configuration as many people have successfully used it.&lt;/li&gt;
  &lt;li&gt;Used the same amount of L2 regularization on all layers, it worked much better to vary the L2 regularization based on which layers started saturating or were clamped against max normal constraints.&lt;/li&gt;
  &lt;li&gt;Used pooling on the layers. Lost too much information between layers, images turned out grainy and poor looking.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The biggest lesson learned dealing with these larger networks is how important it is to getting the weight initializations right. I feel this aspect, after a few other hyperparameters are chosen,  has the largest impact on how well your model will train. It is a good idea to spend time researching the different initialization techniques to understand the impact each has on your model. There are many papers and machine learning libraries out there with different initialization schemes from which you can easily learn.&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;applications&quot; href=&quot;#applications&quot; class=&quot;anchor-link&quot;&gt;
    Applications
  &lt;/a&gt;
&lt;/h2&gt;
&lt;p&gt;Our goal was not to remove or replace the need for other upscaling algorithms, such as bicubic upscaling, but to try to improve quality using different technology and avenues. Our primary use case was to scale lower resolution images up when no higher resolution images are available. This happens occasionally across our platforms.&lt;/p&gt;

&lt;p&gt;Besides the primary use case of still images this technique can be applied to different media formats such as GIFs. The GIF could be split into its separate frames, then scaled up, and then repackaged.&lt;/p&gt;

&lt;p&gt;The final use case that we thought of was saving bandwidth. A smaller image could be sent to the client which would run a client side version of this model to gain a larger image. This could be accomplished using a custom solution or one of the javascript implementations of neural networks available such as &lt;a href=&quot;http://cs.stanford.edu/people/karpathy/convnetjs/&quot;&gt;ConvNetJS&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;furtherSteps&quot; href=&quot;#furtherSteps&quot; class=&quot;anchor-link&quot;&gt;
    Further steps
  &lt;/a&gt;
&lt;/h2&gt;
&lt;p&gt;We feel this problem space has a lot of potential and there are many things to try, including some wild ideas, such as:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Larger filter sizes in the convolutional layers.&lt;/li&gt;
  &lt;li&gt;Try more layers and data.&lt;/li&gt;
  &lt;li&gt;Try different color channel formats instead of RGB.&lt;/li&gt;
  &lt;li&gt;Try using hundreds of filters in the first convolutional layer, sample from them using dropout with a very small inclusion probability and try tweaking the learning rate of the layer.&lt;/li&gt;
  &lt;li&gt;Ditch the fully connected layers and try using all convolutional layers.&lt;/li&gt;
  &lt;li&gt;Curious if &lt;a href=&quot;http://arxiv.org/abs/1503.02531&quot;&gt;distillation&lt;/a&gt; would work with this problem. Might help create a lighter version to run on client devices easily.&lt;/li&gt;
  &lt;li&gt;Look into how small/large we can make the network before the quality starts degrading.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  &lt;a name=&quot;conclusion&quot; href=&quot;#conclusion&quot; class=&quot;anchor-link&quot;&gt;
    Conclusion
  &lt;/a&gt;
&lt;/h2&gt;
&lt;p&gt;Pursuing high fidelity presentation is difficult. As with any endeavor, it takes an exceeding amount of effort to squeeze out those final few percentage points of quality. We are constantly reflecting on our product to see where those percentage points can come from, even if they don’t seem obvious or possible at first. While this wont have its place everywhere within our product, we feel it was a good cursory step forward to improving quality.&lt;/p&gt;

&lt;p&gt;I hope you enjoyed reading through this post and have taken something interesting away with it. I would like to thank everyone at Flipboard for an outstanding internship experience. I have learnt a lot, met many awesome people, and gained invaluable experience in the process.&lt;/p&gt;

&lt;p&gt;If machine learning, large datasets, and working with great people on interesting projects excites you then feel free to apply, &lt;a href=&quot;https://flipboard.com/careers/&quot;&gt;we are hiring&lt;/a&gt;!&lt;/p&gt;

&lt;p&gt;Feel free to follow me on twitter &lt;a href=&quot;https://twitter.com/normantasfi&quot;&gt;@normantasfi&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Special thanks to &lt;a href=&quot;https://twitter.com/charlietuna&quot;&gt;Charles&lt;/a&gt;, &lt;a href=&quot;https://twitter.com/emilsjolander&quot;&gt;Emil&lt;/a&gt;, &lt;a href=&quot;https://twitter.com/anhbmai&quot;&gt;Anh&lt;/a&gt;, &lt;a href=&quot;https://twitter.com/mikeklaas&quot;&gt;Mike Klaas&lt;/a&gt;, and &lt;a href=&quot;https://twitter.com/bapjuseyo&quot;&gt;Michael Johnston&lt;/a&gt; for suggestions and edits throughout the process. Shoutout to &lt;a href=&quot;https://twitter.com/gregoryscallan&quot;&gt;Greg&lt;/a&gt; for always making time to help with server setups and questions.&lt;/em&gt;&lt;/p&gt;

&lt;script type=&quot;text/javascript&quot; src=&quot;https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML&quot;&gt;
&lt;/script&gt;

</description>
                <pubDate>Wed, 06 May 2015 00:00:00 +0000</pubDate>
                <link>http://engineering.flipboard.com//2015/05/scaling-convnets</link>
                <guid isPermaLink="true">http://engineering.flipboard.com//2015/05/scaling-convnets</guid>
            </item>
        
            <item>
                <title>NSUserDefaults Performance Boost</title>
                <author>https://twitter.com/timonus (Tim Johnsen)</author>
                <description>&lt;p&gt;Since iOS 8 was released we’ve noticed some sluggishness when using &lt;a href=&quot;http://flipboard.com&quot;&gt;Flipboard&lt;/a&gt; in the simulator. When taking a trace with Instruments in normal use we noticed a significant amount of time was being spent in &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;CFPreferences&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;.&lt;!--break--&gt;&lt;/p&gt;

&lt;center&gt;
    &lt;div class=&quot;row&quot;&gt;
        &lt;img src=&quot;/assets/nsuserdefaults-performance/before.png&quot; style=&quot;max-width:95%;&quot; /&gt;
    &lt;/div&gt;
&lt;/center&gt;

&lt;p&gt;On Twitter, an Apple engineer acknowledged that there were some changes in iOS 8 that added something called &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;cfprefsd&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;, and that emulating that in the simulator required synchronous reads from disk. This seemed to be the bottleneck we were encountering.&lt;/p&gt;

&lt;center&gt;
	&lt;blockquote class=&quot;twitter-tweet&quot; lang=&quot;en&quot;&gt;&lt;p&gt;&lt;a href=&quot;https://twitter.com/timonus&quot;&gt;@timonus&lt;/a&gt; unfortunately cfprefsd doesn’t currently exist in the simulator, and emulating its behavior requires synchronize disk IO&lt;/p&gt;&amp;mdash; David Smith (@Catfish_Man) &lt;a href=&quot;https://twitter.com/Catfish_Man/status/557977673461268481&quot;&gt;January 21, 2015&lt;/a&gt;&lt;/blockquote&gt;
	&lt;blockquote class=&quot;twitter-tweet&quot; lang=&quot;en&quot; data-conversation=&quot;none&quot;&gt;&lt;p&gt;&lt;a href=&quot;https://twitter.com/timonus&quot;&gt;@timonus&lt;/a&gt; it’s on my list to fix, but it’s a large effort and device took priority&lt;/p&gt;&amp;mdash; David Smith (@Catfish_Man) &lt;a href=&quot;https://twitter.com/Catfish_Man/status/557977746215673856&quot;&gt;January 21, 2015&lt;/a&gt;&lt;/blockquote&gt;
	&lt;script async=&quot;&quot; src=&quot;//platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;
&lt;/center&gt;

&lt;p&gt;About a month ago we were talking as a team about how slow we felt our app had become to debug in the simulator, so we decided to try to do something to speed it up. Our approach was to introduce a man-in-the-middle write-through cache to &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;NSUserDefaults&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; in memory. We do so by swizzling out all of &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;NSUserDefaults&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;’ setters and getters and adding a per-instance &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;NSMutableDictionary&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; to cache values. We avoid compiling this for device builds using &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;TARGET_IPHONE_SIMULATOR&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; because there aren’t such performance issues on device. The increase in performance is dramatic, where we were once spending 80% of our time in &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;CFPreferences&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; we’re now spending 1%.&lt;/p&gt;

&lt;center&gt;
    &lt;div class=&quot;row&quot;&gt;
        &lt;img src=&quot;/assets/nsuserdefaults-performance/after.png&quot; style=&quot;max-width:95%;&quot; /&gt;
    &lt;/div&gt;
&lt;/center&gt;

&lt;p&gt;If you’re seeing performance issues related to &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;NSUserDefaults&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; in the simulator I recommend trying this out, it’s &lt;a href=&quot;https://github.com/Flipboard/NSUserDefaultsSimulatorPerformanceBoost&quot;&gt;open source and available for download on GitHub&lt;/a&gt;. To get started using it all you need to do is include it in your project.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Please note that use of this category may cause side effects when debugging extensions. This is &lt;a href=&quot;https://github.com/Flipboard/NSUserDefaultsSimulatorPerformanceBoost/blob/master/README.md#extensions&quot;&gt;documented&lt;/a&gt; in the GitHub project.&lt;/em&gt;&lt;/p&gt;
</description>
                <pubDate>Mon, 16 Mar 2015 00:00:00 +0000</pubDate>
                <link>http://engineering.flipboard.com//2015/03/nsuserdefaults-performance</link>
                <guid isPermaLink="true">http://engineering.flipboard.com//2015/03/nsuserdefaults-performance</guid>
            </item>
        
            <item>
                <title>Introducing GoldenGate</title>
                <author>https://twitter.com/emilsjolander (Emil Sjölander)</author>
                <description>&lt;p&gt;You might not know it, but both Flipboard for iOS and Flipboard for Android make heavy use of web views. We use web views so we can ensure consistent designs for our partners’ articles across all platforms. Communication between native code and the JavaScript code running in a web view is something that is both tedious to implement as well as very bug prone as it’s mostly just string concatenation. Today we are releasing a library to make this task easier when developing Android applications which use web views.&lt;!--break--&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://www.github.com/flipboard/goldengate&quot; title=&quot;GoldenGate source on GitHub&quot;&gt;GoldenGate&lt;/a&gt; is a annotation processing library which generates java wrappers around your JavaScript code. An annotation processing library is a piece of code which runs when you compile your code and has the ability to generate new java classes. This means that GoldenGate can ensure at compile time that you are sending the correct types into the JavaScript functions you define in your bridge. If you’re interested in knowing more about how to write your own, &lt;a href=&quot;http://hannesdorfmann.com/annotation-processing/annotationprocessing101&quot; title=&quot;Annotation processing blog post&quot;&gt;this blog post&lt;/a&gt; is a good intro.&lt;/p&gt;

&lt;p&gt;Let’s get into a quick example to really show the power of the library! First of all a quick example of how to currently call a JavaScript function in a WebView.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;webview.loadUrl(&quot;javascript:alert(&quot; + myString + &quot;);&quot;);
&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;You should clearly see that a lot can go wrong here which the compiler won’t catch. For example you could misspell &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;alert&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; or maybe &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;myString&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; isn’t a string at all.&lt;/p&gt;

&lt;p&gt;GoldenGate allows for the compiler to have your back. The same code as above written with GoldenGate looks like this.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
2
3
4
5
6
7
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;@Bridge
class JavaScript {
	void alert(String message);
}

JavaScriptBridge bridge = new JavaScript(webview);
bridge.alert(myString);
&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We started by defining an interface which describes the JavaScript methods we want to call from java. This interface is annotated with &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;@Bridge&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; which is where the magic happens. This will generate a class named &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;JavaScriptBridge&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; in this case which implements all the methods defined by the interface.&lt;/p&gt;

&lt;p&gt;There are a couple more options for more advanced usage that we won’t cover in this blog post but they are well documented over on &lt;a href=&quot;http://www.github.com/flipboard/goldengate&quot; title=&quot;GoldenGate source on GitHub&quot;&gt;Github&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;At Flipboard we love the type safety GoldenGate gives us and we think it can help more developers using both native and web technology in their apps. Head over to the &lt;a href=&quot;http://www.github.com/flipboard/goldengate&quot; title=&quot;GoldenGate source on GitHub&quot;&gt;Github repository&lt;/a&gt; to check out the code. Pull requests are very welcome!&lt;/p&gt;

</description>
                <pubDate>Tue, 24 Feb 2015 00:00:00 +0000</pubDate>
                <link>http://engineering.flipboard.com//2015/02/golden-gate</link>
                <guid isPermaLink="true">http://engineering.flipboard.com//2015/02/golden-gate</guid>
            </item>
        
            <item>
                <title>60fps on the mobile web</title>
                <author>https://twitter.com/bapjuseyo (Michael Johnston)</author>
                <description>&lt;p class=&quot;deck&quot;&gt;
Flipboard launched during the dawn of the smartphone and tablet as a mobile-first experience, allowing us to rethink content layout principles from the web for a more elegant user experience on a variety of touchscreen form factors.
&lt;/p&gt;

&lt;p&gt;Now we’re coming full circle and bringing Flipboard to the web. Much of what we do at Flipboard has value independent of what device it’s consumed on: curating the best stories from all the topics, sources, and people that you care about most. Bringing our service to the web was always a logical extension.&lt;/p&gt;

&lt;p&gt;As we began to tackle the project, we knew we wanted to adapt our thinking from our mobile experience to try and elevate content layout and interaction on the web. We wanted to match the polish and performance of our native apps&lt;!--break--&gt;, but in a way that felt true to the browser.&lt;/p&gt;

&lt;p&gt;Early on, after testing numerous prototypes, we decided our web experience should scroll. Our mobile apps are known for their book-like pagination metaphor, something that feels intuitive on a touch screen, but for a variety of reasons, scrolling feels most natural on the web.&lt;/p&gt;

&lt;p&gt;In order to &lt;a href=&quot;http://www.html5rocks.com/en/tutorials/speed/scrolling/&quot;&gt;optimize scrolling performance&lt;/a&gt;, we knew that we needed to keep paint times below 16ms and limit reflows and repaints. This is especially important during animations. To avoid painting during animations there are two properties you can safely animate: CSS transform and opacity. But that really limits your options.&lt;/p&gt;

&lt;p&gt;What if you want to animate the width of an element?&lt;/p&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
  &lt;img src=&quot;/assets/mobileweb/follow_btn.gif&quot; style=&quot;border: 1px solid #ddd;&quot; alt=&quot;Follow button animation&quot; /&gt;
&lt;/p&gt;

&lt;p&gt;How about a frame-by-frame scrolling animation?&lt;/p&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
  &lt;img src=&quot;/assets/mobileweb/topbar.gif&quot; style=&quot;border: 1px solid #ddd;&quot; alt=&quot;Clipping animation&quot; /&gt;
&lt;/p&gt;

&lt;p&gt;(Notice in the above image that the icons at the top transition from white to black. These are 2 separate elements overlaid on each other whose bounding boxes are clipped depending on the content beneath.)&lt;/p&gt;

&lt;p&gt;These types of animations have always suffered from &lt;a href=&quot;http://jankfree.org/&quot;&gt;jank&lt;/a&gt; on the web, particularly on mobile devices, for one simple reason:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The DOM is too slow.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It’s not just slow, it’s really slow. If you touch the DOM in any way during an animation you’ve already blown through your 16ms frame budget.&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;EnterCanvas&quot; href=&quot;#EnterCanvas&quot; class=&quot;anchor-link&quot;&gt;
    Enter &amp;lt;canvas&amp;gt;
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;Most modern mobile devices have hardware-accelerated canvas, so why couldn’t we take advantage of this? &lt;a href=&quot;http://chrome.angrybirds.com/&quot;&gt;HTML5 games&lt;/a&gt; certainly do.  But could we really develop an application user interface in canvas?&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;DrawingModes&quot; href=&quot;#DrawingModes&quot; class=&quot;anchor-link&quot;&gt;
    Immediate mode vs. retained mode
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;Canvas is an immediate mode drawing API, meaning that the drawing surface retains no information about the objects drawn into it. This is in opposition to retained mode, which is a declarative API that maintains a hierarchy of objects drawn into it.&lt;/p&gt;

&lt;p&gt;The advantage to retained mode APIs is that they are typically easier to construct complex scenes with, e.g. the DOM for your application. It often comes with a performance cost though, as additional memory is required to hold the scene and updating the scene can be slow.&lt;/p&gt;

&lt;p&gt;Canvas benefits from the immediate mode approach by allowing drawing commands to be sent directly to the GPU. But using it to build user interfaces requires a higher level abstraction to be productive. For instance something as simple as drawing one element on top of another can be problematic when resources load asynchronously, such as drawing text on top of an image. In HTML this is easily achieved with the ordering of elements or z-index in CSS.&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;CanvasUI&quot; href=&quot;#CanvasUI&quot; class=&quot;anchor-link&quot;&gt;
    Building a UI in &amp;lt;canvas&amp;gt;
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;Canvas lacks many of the abilities taken for granted in HTML + CSS.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;CanvasText&quot; href=&quot;#CanvasText&quot; class=&quot;anchor-link&quot;&gt;
    Text
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;There is a single API for drawing text: &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;fillText(text, x, y [, maxWidth])&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;. This function accepts three arguments: the text string and x-y coordinates to begin drawing. But canvas can only draw a single line of text at a time. If you want text wrapping, you need to write your own function.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;CanvasImages&quot; href=&quot;#CanvasImages&quot; class=&quot;anchor-link&quot;&gt;
    Images
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;To draw an image into a canvas you call &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;drawImage()&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt;. This is a variadic function where the more arguments you specify the more control you have over positioning and clipping. But canvas does not care if the image has loaded or not so make sure this is called only after the image load event.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;CanvasOverlapping&quot; href=&quot;#CanvasOverlapping&quot; class=&quot;anchor-link&quot;&gt;
    Overlapping elements
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;In HTML and CSS it’s easy to specify that one element should be rendered on top of another by using the order of the elements in the DOM or CSS z-index. But remember, canvas is an immediate mode drawing API. When elements overlap and either one of them needs to be redrawn, both have to be redrawn in the same order (or at least the dirtied parts).&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;CanvasFonts&quot; href=&quot;#CanvasFonts&quot; class=&quot;anchor-link&quot;&gt;
    Custom fonts
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;Need to use a custom web font? The canvas text API does not care if a font has loaded or not. You need a way to know when a font has loaded, and redraw any regions that rely on that font. Fortunately, modern browsers have a &lt;a href=&quot;http://dev.w3.org/csswg/css-font-loading/&quot;&gt;promise-based API&lt;/a&gt; for doing just that. Unfortunately, iOS WebKit (iOS 8 at the time of this writing) does not support it.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;CanvasBenefits&quot; href=&quot;#CanvasBenefits&quot; class=&quot;anchor-link&quot;&gt;
    Benefits of &amp;lt;canvas&amp;gt;
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;Given all these drawbacks, one might begin to question selecting the canvas approach over DOM. In the end, our decision was made simple by one simple truth:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;You cannot build a 60fps scrolling list view with DOM.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Many (including us) have tried and failed. Scrollable elements are possible in pure HTML and CSS with &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;overflow: scroll&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; (combined with &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;-webkit-overflow-scrolling: touch&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; on iOS) but these do not give you frame-by-frame control over the scrolling animation and mobile browsers have a difficult time with long, complex content.&lt;/p&gt;

&lt;p&gt;In order to build an infinitely scrolling list with reasonably complex content, we needed the equivalent of &lt;a href=&quot;https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/index.html&quot;&gt;UITableView&lt;/a&gt; for the web.&lt;/p&gt;

&lt;p&gt;In contrast to the DOM, most devices today have hardware accelerated canvas implementations which send drawing commands directly to the GPU. This means we could render elements incredibly fast; we’re talking sub-millisecond range in many cases.&lt;/p&gt;

&lt;p&gt;Canvas is also a very small API when compared to HTML + CSS, reducing the surface area for bugs or inconsistencies between browsers. There’s a reason there is no &lt;a href=&quot;http://caniuse.com/&quot;&gt;Can I Use?&lt;/a&gt; equivalent for canvas.&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;FasterDOM&quot; href=&quot;#FasterDOM&quot; class=&quot;anchor-link&quot;&gt;
    A faster DOM abstraction
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;As mentioned earlier, in order to be somewhat productive, we needed a higher level of abstraction than simply drawing rectangles, text and images in immediate mode. We built a very small abstraction that allows a developer to deal with a tree of nodes, rather than a strict sequence of drawing commands.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;RenderLayer&quot; href=&quot;#RenderLayer&quot; class=&quot;anchor-link&quot;&gt;
    RenderLayer
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;A RenderLayer is the base node by which other nodes build upon. Common properties such as top, left, width, height, backgroundColor and zIndex are expressed at this level. A RenderLayer is nothing more than a plain JavaScript object containing these properties and an array of children.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;RenderImage&quot; href=&quot;#RenderImage&quot; class=&quot;anchor-link&quot;&gt;
    Image
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;There are Image layers which have additional properties to specify the image URL and cropping information. You don’t have to worry about listening for the image load event, as the Image layer will do this for you and send a signal to the drawing engine that it needs to update.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;RenderText&quot; href=&quot;#RenderText&quot; class=&quot;anchor-link&quot;&gt;
    Text
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;Text layers have the ability to render multi-line truncated text, something which is incredibly expensive to do in DOM. Text layers also support custom font faces, and will do the work of updating when the font loads.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;RenderComposition&quot; href=&quot;#RenderComposition&quot; class=&quot;anchor-link&quot;&gt;
    Composition
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;These layers can be composed to build complex interfaces. Here is an example of a RenderLayer tree:&lt;/p&gt;

&lt;pre&gt;
{
  frame: [0, 0, 320, 480],
  backgroundColor: '#fff',
  children: [
    {
      type: 'image',
      frame: [0, 0, 320, 200],
      imageUrl: 'http://lorempixel.com/360/420/cats/1/'
    },
    {
      type: 'text',
      frame: [10, 210, 300, 260],
      text: 'Lorem ipsum...',
      fontSize: 18,
      lineHeight: 24
    }
  ]
}
&lt;/pre&gt;

&lt;h3&gt;
  &lt;a name=&quot;InvalidatingLayers&quot; href=&quot;#InvalidatingLayers&quot; class=&quot;anchor-link&quot;&gt;
    Invalidating layers
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;When a layer needs to be redrawn, for instance after an image loads, it sends a signal to the drawing engine that its frame is dirty. Changes are batched using &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;requestAnimationFrame&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; to avoid &lt;a href=&quot;http://wilsonpage.co.uk/preventing-layout-thrashing/&quot;&gt;layout thrashing&lt;/a&gt; and in the next frame the canvas redraws.&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;Scrolling60fps&quot; href=&quot;#Scrolling60fps&quot; class=&quot;anchor-link&quot;&gt;
    Scrolling at 60fps
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;Perhaps the one aspect of the web we take for granted the most is how a browser scrolls a web page. Browser vendors have gone to &lt;a href=&quot;http://www.chromium.org/developers/design-documents/gpu-accelerated-compositing-in-chrome&quot;&gt;great lengths&lt;/a&gt; to improve scrolling performance.&lt;/p&gt;

&lt;p&gt;It comes with a tradeoff though. In order to scroll at 60fps on mobile, browsers used to halt JavaScript execution during scrolling for fear of DOM modifications causing reflow. Recently, iOS and Android have exposed &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;onscroll&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; events that work more like they do on desktop browsers but your mileage may vary if you are trying to keep DOM elements synchronized with the scroll position.&lt;/p&gt;

&lt;p&gt;Luckily, browser vendors are aware of the problem. In particular, the Chrome team has been &lt;a href=&quot;http://updates.html5rocks.com/2014/05/A-More-Compatible-Smoother-Touch&quot;&gt;open&lt;/a&gt; about its efforts to improve this situation on mobile.&lt;/p&gt;

&lt;p&gt;Turning back to canvas, the short answer is you have to implement scrolling in JavaScript.&lt;/p&gt;

&lt;p&gt;The first thing you need is a way to compute scrolling momentum. If you don’t want to do the math the folks at Zynga open sourced a &lt;a href=&quot;https://github.com/zynga/scroller&quot;&gt;pure logic scroller&lt;/a&gt; that fits well with any layout approach.&lt;/p&gt;

&lt;p&gt;The technique we use for scrolling uses a single canvas element. At each touch event, the current render tree is updated by translating each node by the current scroll offset. The entire render tree is then redrawn with the new frame coordinates.&lt;/p&gt;

&lt;p&gt;This sounds like it would be incredibly slow, but there is an important optimization technique that can be used in canvas where the result of drawing operations can be cached in an off-screen canvas. The off-screen canvas can then be used to redraw that layer at a later time.&lt;/p&gt;

&lt;p&gt;This technique can be used not just for image layers, but text and shapes as well. The two most expensive drawing operations are filling text and drawing images. But once these layers are drawn once, it is very fast to redraw them using an off-screen canvas.&lt;/p&gt;

&lt;p&gt;In the demonstration below, each page of content is divided into 2 layers: an image layer and a text layer. The text layer contains multiple elements that are grouped together. At each frame in the scrolling animation, the 2 layers are redrawn using cached bitmaps.&lt;/p&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
  &lt;img src=&quot;/assets/mobileweb/scrolling.gif&quot; style=&quot;border: 1px solid #ddd; width: 320px; height: auto;&quot; alt=&quot;Scrolling timeline&quot; /&gt;
&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;ObjectPooling&quot; href=&quot;#ObjectPooling&quot; class=&quot;anchor-link&quot;&gt;
    Object pooling
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;During the course of scrolling through an infinite list of items, a significant number of RenderLayers must be set up and torn down. This can create a lot of garbage, which would halt the main thread when collected.&lt;/p&gt;

&lt;p&gt;To avoid the amount of garbage created, RenderLayers and associated objects are aggressively pooled. This means only a relatively small number of layer objects are ever created. When a layer is no longer needed, it is released back into the pool where it can later be reused.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;FastSnapshotting&quot; href=&quot;#FastSnapshotting&quot; class=&quot;anchor-link&quot;&gt;
    Fast snapshotting
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;The ability to cache composite layers leads to another advantage: the ability to treat portions of rendered structures as a bitmap. Have you ever needed to take a snapshot of only part of a DOM structure? That’s incredibly fast and easy when you render that structure in canvas.&lt;/p&gt;

&lt;p&gt;The UI for flipping an item into a magazine leverages this ability to perform a smooth transition from the timeline. The snapshot contains the entire item, minus the top and bottom chrome.&lt;/p&gt;

&lt;p style=&quot;text-align: center&quot;&gt;
  &lt;img src=&quot;/assets/mobileweb/flip_ui.gif&quot; style=&quot;border: 1px solid #ddd;&quot; alt=&quot;Flipping an item into a magazine&quot; /&gt;
&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;DeclarativeAPI&quot; href=&quot;#DeclarativeAPI&quot; class=&quot;anchor-link&quot;&gt;
    A declarative API
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;We had the basic building blocks of an application now. However, imperatively constructing a tree of RenderLayers could be tedious. Wouldn’t it be nice to have a declarative API, similar to how the DOM worked?&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;React&quot; href=&quot;#React&quot; class=&quot;anchor-link&quot;&gt;
    React
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;We are big fans of &lt;a href=&quot;http://facebook.github.io/react/&quot;&gt;React&lt;/a&gt;. Its single directional data flow and declarative API have changed the way people build apps. The most compelling feature of React is the virtual DOM. The fact that it renders to HTML in a browser container is simply an implementation detail. The recent introduction of &lt;a href=&quot;https://www.youtube.com/watch?v=KVZ-P-ZI6W4&quot;&gt;React Native&lt;/a&gt; proves this out.&lt;/p&gt;

&lt;p&gt;What if we could bind our canvas layout engine to React components?&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;ReactCanvas&quot; href=&quot;#ReactCanvas&quot; class=&quot;anchor-link&quot;&gt;
    Introducing React Canvas
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/flipboard/react-canvas&quot;&gt;React Canvas&lt;/a&gt; adds the ability for React components to render to &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;&amp;lt;canvas&amp;gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; rather than DOM.&lt;/p&gt;

&lt;p&gt;The first version of the canvas layout engine looked very much like imperative view code. If you’ve ever done DOM construction in JavaScript you’ve probably run across code like this:&lt;/p&gt;

&lt;pre&gt;
// Create the parent layer
var root = RenderLayer.getPooled();
root.frame = [0, 0, 320, 480];

// Add an image
var image = RenderLayer.getPooled('image');
image.frame = [0, 0, 320, 200];
image.imageUrl = 'http://lorempixel.com/360/420/cats/1/';
root.addChild(image);

// Add some text
var label = RenderLayer.getPooled('text');
label.frame = [10, 210, 300, 260];
label.text = 'Lorem ipsum...';
label.fontSize = 18;
label.lineHeight = 24;
root.addChild(label);
&lt;/pre&gt;

&lt;p&gt;Sure, this works but who wants to write code this way? In addition to being error-prone it’s difficult to visualize the rendered structure.&lt;/p&gt;

&lt;p&gt;With React Canvas this becomes:&lt;/p&gt;

&lt;pre&gt;
var MyComponent = React.createClass({
  render: function () {
    return (
      &amp;lt;Group style={styles.group}&amp;gt;
        &amp;lt;Image style={styles.image} src='http://...' /&amp;gt;
        &amp;lt;Text style={styles.text}&amp;gt;
          Lorem ipsum...
        &amp;lt;/Text&amp;gt;
      &amp;lt;/Group&amp;gt;
    );
  }
});

var styles = {
  group: {
    left: 0,
    top: 0,
    width: 320,
    height: 480
  },

  image: {
    left: 0,
    top: 0,
    width: 320,
    height: 200
  },

  text: {
    left: 10,
    top: 210,
    width: 300,
    height: 260,
    fontSize: 18,
    lineHeight: 24
  }
};
&lt;/pre&gt;

&lt;p&gt;You may notice that everything appears to be absolutely positioned. That’s correct. Our canvas rendering engine was born out of the need to drive pixel-perfect layouts with multi-line ellipsized text. This cannot be done with conventional CSS, so an approach where everything is absolutely positioned fit well for us. However, this approach is not well-suited for all applications.&lt;/p&gt;

&lt;h3&gt;
  &lt;a name=&quot;css-layout&quot; href=&quot;#css-layout&quot; class=&quot;anchor-link&quot;&gt;
    css-layout
  &lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;Facebook recently open sourced its &lt;a href=&quot;https://github.com/facebook/css-layout&quot;&gt;JavaScript implementation of CSS&lt;/a&gt;. It supports a subset of CSS like margin, padding, position and most importantly flexbox.&lt;/p&gt;

&lt;p&gt;Integrating css-layout into React Canvas was a matter of hours. Check out the &lt;a href=&quot;https://github.com/flipboard/react-canvas/blob/master/examples/css-layout/app.js&quot;&gt;example&lt;/a&gt; to see how this changes the way components are styled.&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;DeclarativeInfiniteScrolling&quot; href=&quot;#DeclarativeInfiniteScrolling&quot; class=&quot;anchor-link&quot;&gt;
    Declarative infinite scrolling
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;How do you create a &lt;em&gt;60fps&lt;/em&gt; infinite, paginated scrolling list in React Canvas?&lt;/p&gt;

&lt;p&gt;It turns out this is quite easy because of React’s diffing of the virtual DOM. In &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;render()&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; only the currently visible elements are returned and React takes care of updating the virtual DOM tree as needed during scrolling.&lt;/p&gt;

&lt;pre&gt;
var ListView = React.createClass({
  getInitialState: function () {
    return {
      scrollTop: 0
    };
  },

  render: function () {
    var items = this.getVisibleItemIndexes().map(this.renderItem);
    return (
      &amp;lt;Group
        onTouchStart={this.handleTouchStart}
        onTouchMove={this.handleTouchMove}
        onTouchEnd={this.handleTouchEnd}
        onTouchCancel={this.handleTouchEnd}&amp;gt;
        {items}
      &amp;lt;/Group&amp;gt;
    );
  },

  renderItem: function (itemIndex) {
    // Wrap each item in a &amp;lt;Group&amp;gt; which is translated up/down based on
    // the current scroll offset.
    var translateY = (itemIndex * itemHeight) - this.state.scrollTop;
    var style = { translateY: translateY };
    return (
      &amp;lt;Group style={style} key={itemIndex}&amp;gt;
        &amp;lt;Item /&amp;gt;
      &amp;lt;/Group&amp;gt;
    );
  },

  getVisibleItemIndexes: function () {
    // Compute the visible item indexes based on `this.state.scrollTop`.
  }
});
&lt;/pre&gt;

&lt;p&gt;To hook up the scrolling, we use the &lt;a href=&quot;https://github.com/zynga/scroller&quot;&gt;Scroller&lt;/a&gt; library to &lt;code class=&quot;highlighter-rouge&quot;&gt;&lt;table class=&quot;rouge-table&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;rouge-gutter gl&quot;&gt;&lt;pre class=&quot;lineno&quot;&gt;1
&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;rouge-code&quot;&gt;&lt;pre&gt;setState()&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/code&gt; on our ListView component.&lt;/p&gt;

&lt;pre&gt;
...

// Create the Scroller instance on mount.
componentDidMount: function () {
  this.scroller = new Scroller(this.handleScroll);
},

// This is called by the Scroller at each scroll event.
handleScroll: function (left, top) {
  this.setState({ scrollTop: top });
},

handleTouchStart: function (e) {
  this.scroller.doTouchStart(e.touches, e.timeStamp);
},

handleTouchMove: function (e) {
  e.preventDefault();
  this.scroller.doTouchMove(e.touches, e.timeStamp, e.scale);
},

handleTouchEnd: function (e) {
  this.scroller.doTouchEnd(e.timeStamp);
}

...
&lt;/pre&gt;

&lt;p&gt;Though this is a simplified version it showcases some of React’s best qualities. Touch events are declaratively bound in render(). Each touchmove event is forwarded to the Scroller which computes the current scroll top offset. Each scroll event emitted from the Scroller updates the state of the ListView component, which renders only the currently visible items on screen. All of this happens in under 16ms because &lt;a href=&quot;http://calendar.perfplanet.com/2013/diff/&quot;&gt;React’s diffing algorithm is very fast&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;See the &lt;a href=&quot;https://github.com/flipboard/react-canvas/blob/master/lib/ListView.js&quot;&gt;ListView source code&lt;/a&gt; for the complete implementation.&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;PracticalApplications&quot; href=&quot;#PracticalApplications&quot; class=&quot;anchor-link&quot;&gt;
    Practical applications
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;React Canvas is not meant to completely replace the DOM. We utilize it in performance-critical rendering paths in our mobile web app, primarily the scrolling timeline view.&lt;/p&gt;

&lt;p&gt;Where rendering performance is not a concern, DOM may be a better approach. In fact, it’s the only approach for certain elements such as input fields and audio/video.&lt;/p&gt;

&lt;p&gt;In a sense, Flipboard for mobile web is a hybrid application. Rather than blending native and web technologies, it’s all web content. It mixes DOM-based UI with canvas rendering where appropriate.&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;Accessibility&quot; href=&quot;#Accessibility&quot; class=&quot;anchor-link&quot;&gt;
    A word on accessibility
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;This area needs further exploration. Using fallback content (the canvas DOM sub-tree) should allow screen readers such as VoiceOver to interact with the content. We’ve seen mixed results with the devices we’ve tested. Additionally there is a standard for &lt;a href=&quot;http://www.w3.org/TR/2010/WD-2dcontext-20100304/#dom-context-2d-drawfocusring&quot;&gt;focus management&lt;/a&gt; that is not supported by browsers yet.&lt;/p&gt;

&lt;p&gt;One approach that was raised by &lt;a href=&quot;http://vimeo.com/3195079&quot;&gt;Bespin&lt;/a&gt; in 2009 is to keep a &lt;a href=&quot;http://robertnyman.com/2009/04/03/mozilla-labs-online-code-editor-bespin/#comment-560310&quot;&gt;parallel DOM&lt;/a&gt; in sync with the elements rendered in canvas. We are continuing to investigate the right approach to accessibility.&lt;/p&gt;

&lt;h2&gt;
  &lt;a name=&quot;Conclusion&quot; href=&quot;#Conclusion&quot; class=&quot;anchor-link&quot;&gt;
    Conclusion
  &lt;/a&gt;
&lt;/h2&gt;

&lt;p&gt;In the pursuit of &lt;em&gt;60fps&lt;/em&gt; we sometimes resort to extreme measures. Flipboard for mobile web is a case study in pushing the browser to its limits. While this approach may not be suitable for all applications, for us it’s enabled a level of interaction and performance that rivals native apps. We hope that by releasing the work we’ve done with &lt;a href=&quot;https://github.com/flipboard/react-canvas&quot;&gt;React Canvas&lt;/a&gt; that other compelling use cases might emerge.&lt;/p&gt;

&lt;p&gt;Head on over to &lt;a href=&quot;https://flipboard.com/&quot;&gt;flipboard.com&lt;/a&gt; on your phone to see what we’ve built, or if you don’t have a Flipboard account, check out a &lt;a href=&quot;https://flipboard.com/@flipboard/flipboard-picks-8a1uu7ngz&quot;&gt;couple&lt;/a&gt; of &lt;a href=&quot;https://flipboard.com/@flipboard/ten-for-today-k6ln1khuz&quot;&gt;magazines&lt;/a&gt; to get a taste of Flipboard on the web. Let us know what you think.&lt;/p&gt;
</description>
                <pubDate>Tue, 10 Feb 2015 00:00:00 +0000</pubDate>
                <link>http://engineering.flipboard.com//2015/02/mobile-web</link>
                <guid isPermaLink="true">http://engineering.flipboard.com//2015/02/mobile-web</guid>
            </item>
        
    </channel>
</rss>
