<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tyler Lanigan on Medium]]></title>
        <description><![CDATA[Stories by Tyler Lanigan on Medium]]></description>
        <link>https://medium.com/@tyler-lanigan-hs?source=rss-f7c2706c2619------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Zy8MeduczH4s17T5tU-LbQ.png</url>
            <title>Stories by Tyler Lanigan on Medium</title>
            <link>https://medium.com/@tyler-lanigan-hs?source=rss-f7c2706c2619------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:57:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tyler-lanigan-hs/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Suggesting Social Media Posts Using Collaborative Filtering]]></title>
            <link>https://medium.com/hootsuite-engineering/suggesting-social-media-posts-using-collaborative-filtering-2f5450afb12f?source=rss-f7c2706c2619------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f5450afb12f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[hootsuite]]></category>
            <category><![CDATA[collaborative-filtering]]></category>
            <category><![CDATA[content-recommendation]]></category>
            <dc:creator><![CDATA[Tyler Lanigan]]></dc:creator>
            <pubDate>Wed, 30 Jun 2021 22:22:52 GMT</pubDate>
            <atom:updated>2021-07-12T23:57:33.563Z</atom:updated>
            <content:encoded><![CDATA[<p>In 2020, the Machine Learning team at Hootsuite partnered with the Amplify team to create the Post Recommendation feature: a system that recommends social media posts to share based on what content a user has shared in the past. The goal was to increase the amount of content shared through Amplify and make it easier to find engaging content for our users. This post outlines the techniques used and the system architecture for this feature. As well, the performance in production will be discussed. Below in <em>Figure 1</em> is a screenshot of the front facing design of the recommendation section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CNq_8xp7BQr1f-Kc" /><figcaption>Figure 1: Suggested Post UI Design</figcaption></figure><h3>Background</h3><p>Amplify is a product made by Hootsuite that allows companies to increase the reach of their content on social media by sharing it through the social media accounts of their employees. Employees have access to a dashboard of the company’s content and can choose to share it to their own networks. One of the current issues that the amplify team is trying to solve is that some companies produce a lot of content that may or may not be relevant to each user’s tastes. You wouldn’t want to share a post out to your network about, for example stock information, if your personal network expects you to always be posting articles about awesome rock bands such as Led Zeppelin, or Foo Fighters.</p><h3>Collaborative Filtering</h3><p>A popular technique for content recommendation is called collaborative filtering. Collaborative filtering can be summarized with the following example: user A shares post 1, and user B shares post 1 and post 2. Since user A and user B both shared post 1 it can be assumed that they have similar tastes. Therefore, it would make sense to recommend post 2 to user A. The real implementation details for collaborative filtering are a little more sophisticated, and will involve different ways of scoring each posts and how similar users are based on their posting habits, but that is the general gist.</p><p>The specific type of collaborative filtering that we chose to use in this project is Singular Value Decomposition (SVD). SVD gained popularity after it was used to win the 1 million dollar Netflix recommendation algorithm competition. To read more about that competition and how this algorithm was adapted for collaborative filtering check out this <a href="https://www.thrillist.com/entertainment/nation/the-netflix-prize">blog post</a>. The implementation that we used was from the <a href="http://surpriselib.com/">surprise library</a>.</p><p>Let’s dive a little into how SVD works. SVD at its core relies on ratings that users supply for items in order to inform making predictions on how a user would rate a new item. Making a recommendation from this is as simple as predicting how a user would rate all items that they have not interacted with (in this case shared) and sorting that list to return to the user. In order to make this prediction, first we construct a matrix where each row represents a user, and each column represents an item. The elements of this matrix are the ratings that are given to items by users. The diagram in <em>Figure 2</em> below shows the rating matrix on the left side of the equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aESdtRl6LRYpEFHY" /><figcaption>Figure 2: Collaborative Filtering in a Nutshell</figcaption></figure><p>Through some linear algebra this matrix can be decomposed into a user embedding matrix and a post embedding matrix. If you would like to see some details on how this works, please refer to this <a href="https://towardsdatascience.com/various-implementations-of-collaborative-filtering-100385c6dfe0">excellent article</a>. However what is important to understand is that this decomposition can take place even if there are values missing from the ratings matrix. What this means is that, using the user embedding matrix and the post embedding matrix obtained from the decomposition, predicted ratings for each user item pair can be obtained by multiplying the corresponding user row and post column together from these two matrices. Thus the ratings matrix can be filled in with the missing values. All that remains is to filter the matrix for posts that have already been shared, and present the posts that have the highest predicted rating to the user as recommendations. This is how a basic recommendation system works!</p><h3>Implicit Rating</h3><p>The Amplify product does not currently have a way for users to rate pieces of content that they share. This presents a problem as, in order to decompose the ratings matrix into a user matrix and a post matrix, you need to have some initial values filled-in (analogous to training data in supervised problems). In fact, the more you initially have, the better you should expect the system to perform (however you can’t have them all filled in or else there wouldn’t be anything for the system to predict) However, this problem can be overcome by using <strong><em>implicit</em> <em>ratings</em></strong> instead of explicit ratings.</p><p>So what is an <strong><em>implicit</em></strong> vs <strong><em>explicit</em></strong> rating? Explicit ratings, like a 5 star rating given to items on Amazon, are provided by the users and are intentional. Implicit ratings are inferred from the actions of users. E.g on Netflix, if they watched a movie, and for how long they watched it.</p><p>In the case of our system we use a read event from the user, and a share event from the user in order to form our implicit rating. We also hypothesize that incorporating if the user has customized the post by adding their own text would improve our results, however this has not yet been implemented.</p><p>As a point of interest, we found that a large portion of our users share posts without reading them! See the pie graph in <em>Figure 3</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*B_oGj6ywYWK9Iagb" /><figcaption>Figure 3: Pie graph showing that our users do not read posts</figcaption></figure><p>Hopefully our recommendation engine will encourage users to read the posts before sharing them!</p><h3>System Architecture</h3><p>The system architecture for our recommendation engine is shown in <em>Figure 4</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/0*pEVWQu5gYKkdrUnE" /><figcaption>Figure 4: System Architecture</figcaption></figure><p>This is a similar design to previous systems that our team has built (<a href="https://medium.com/hootsuite-engineering/the-suggested-tags-service-c8dc57d9efe5">The Suggested Tag Service</a>, and the <a href="https://medium.com/hootsuite-engineering/the-suggested-reply-feature-d35c928324d8">Suggested Reply Service</a>), with a new addition of hosting the prediction endpoint on Kubernetes. Previously the prediction endpoints were hosted on AWS Sagemaker, however we made the decision to move off of it as it was restrictive and did not allow us to integrate into the system of tooling that Hootsuite develops for general usage from each of our dev teams.</p><p>The flow is as follows: a user will share or read an article on Amplify. This emits an event to our Kafka stream that is ingested by an ingestion service into S3. The data is processed and augmented using a Spark job that calls an eternal id to add necessary information, then put back into S3 as processed data. Then we use AWS Sagemaker to make a training job that will take this processed data and produce a model. This model can then be deployed in a Flask based Kubernetes service from which the front end will ask for predictions!</p><h3>Filtering</h3><p>As Hootsuite is an international company, not all of our users share posts in the same language. In fact, some of the companies that are our customers have posts in multiple languages. With that being said, we don’t want our recommendation system to make a recommendation to a user outside of their language. Thus, we use a language detection library in Python (currently <a href="https://pypi.org/project/langdetect/">langdetect</a> but in the process of moving to <a href="https://fasttext.cc/blog/2017/10/02/blog-post.html">fastText</a> as it is, as its name suggests, fast) to generate maps of the post ids and what their languages are. We then only suggest posts that are the same language as what a given user has shared or read in the past.</p><h3>Metrics</h3><p>This section is a bit of a slog, but is important when you are building recommendation engine. Measuring a recommendation system performance using accuracy is sort of an anti-pattern. If you use accuracy you assume that the best system is one that would recommend posts that a user definitely would have shared. What is more desirable is to recommend posts that a user would not have thought of, but in which they still genuinely find value. Thus our team looked into a few different metrics to use.</p><p><strong>Diversity — </strong>measures how narrow or wide the spectrum of recommended products are to <strong>a single user</strong>. A recommender that only recommends the music of one topic of post is pretty narrow; one that recommends across multiple topics is more diverse.</p><p><strong>Coverage — </strong>reflects the degree to which the generated recommendations cover the catalog of available items, wider coverage increases user’s satisfaction. Coverage is not defined at the level of an individual user, but rather <strong>at the level of the system</strong> [1].</p><p>High diversity != high coverage, eg: if different users are recommended the same diverse set of items, the average diversity of the system will be high, but the coverage will remain low. Diversity is to measure per user’s recommendation, while coverage is a system level measurement.</p><p><strong>Novelty — </strong>measures how new, original, or unusual the recommendations are for the user. In general, recommendations will mostly consist of popular items because (i) popular items have more data and (ii) popular items do well in offline and online evaluations.</p><p>In the end we chose to add <strong>Coverage</strong> as a metric that we tracked and potentially optimized for. We dropped computing diversity since the computation takes a long time and is not practical during production; we also dropped novelty, as after discussing with our stakeholders, it was not a trait that they desired.</p><p>We tried two methods to boost the aggregated coverage score. The first method forces a random post for each member. Such randomness is controlled by a randomness seed value and an accuracy threshold (how confident the model is in its predictions). A hyper-parameter search suggests that using a threshold=0.5 and randomness factor of 42 yields an aggregated coverage score of around 0.77, which seems reasonable to use in production.</p><p>Another method we attempted uses a specific formula to re-rank the list of recommended posts per member, where the formula gives more weight to posts that are not in the <em>top_k</em> recommended items and less weight to posts that are one of the <em>top_k</em> recommended items. This method also provides a few tune-able hyper-parameters, however, after experimentation, the results were not ideal and took fairly long time to compute.</p><p>Therefore, we chose the first method of using a randomly inserted post to boost the recommendation coverage.</p><h3>System Monitoring and Detecting Crashes</h3><p>In order to detect when performance is dropping, or when our inference service is not returning predictions, we built dashboards using <a href="https://newrelic.com/lp/grafana-monitoring?utm_campaign=Grafana-NORAM&amp;utm_medium=cpc&amp;utm_source=google&amp;utm_content=GRF_LP&amp;fiscal_year=FY21&amp;quarter=Q2&amp;gtm=DEV&amp;program=DE&amp;ad_type=TXT&amp;geo=AMER&amp;utm_term=grafana&amp;utm_device=c&amp;_bt=452933284758&amp;_bm=e&amp;_bn=g&amp;gclid=CjwKCAjwieuGBhAsEiwA1Ly_nZQ9gOoeEUZUeVWP9OP6kMSGm6Lhk8njG9BJ2noBhHgjs3KAnvqfCBoChMQQAvD_BwE">Grafana</a>. This allows us to detect when the system is returning values too slowly, or returning errors. We can then be alerted via Slack so we can take quick action.</p><h3>Retraining</h3><p>The system retrains on a daily cadence. The ingestion service is constantly streaming data into the training buckets and if we wanted to, we could decrease the cadence down to an hour, which is the time that it takes new models to train in Sagemaker. However it was deemed that a daily retrain is acceptable.</p><h3>Production Metrics</h3><p>In order to measure how well this system works in production we use a standard acceptance rate. How often does a user share a post when they see a recommendation from our system. This metric can be seen in <em>Figure 5</em> showing a graph that we made using <a href="https://mixpanel.com/get-demo/best-product-analytics/?utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=Search-Google-CA-Brand-MB-GP&amp;utm_content=brand&amp;utm_term=%2Bmixpanel&amp;theme=&amp;gclid=CjwKCAjwrPCGBhALEiwAUl9X07Te5TYWe6UDJqZdXsNNpOzZJWBhlgVCXhMftwJLj_N4Ed8UUVlMHxoCqaAQAvD_BwE">Mixpanel</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gN0f5jxQ3JCw_YkA" /><figcaption>Figure 5: Mixpanel Metrics</figcaption></figure><p>On average the posts are shared roughly 28% of the time, which our team is fairly happy with. In order to improve results, we are looking to use <a href="https://en.wikipedia.org/wiki/Bayesian_optimization">Bayesian Optimization</a> on the model parameters and incorporate different elements in our calculation of the implicit rating for each user. We also have looked into doing A/B tests where we present a different amount of suggestions for each variant. Currently the system will make a decision for how many to present based on its confidence level; however, we can see using Mixpanel to drill into our results, that users that are presented with 3 recommendations only have a higher success rate. This suggests that an experiment where a random sub-sample of users are presented with a fixed number of recommendations is in order. The results we noted from this Mixpanel analysis are shown in Table 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPVTyn2PHmRsRc_ucO-g1g.png" /><figcaption>Table 1: Mixpanel Analysis results.</figcaption></figure><h3>Conclusion</h3><p>Recommendation systems are ubiquitous on the internet. They help increase customers usage of your business because they help customers find what they are looking for. Hopefully this blog post will help you if you are thinking of implementing your own.</p><p>With that being said I have a list of people I would like to thank my teammates on the Machine Learning Team for working hard to deliver the Suggested Post project (<a href="https://medium.com/u/d94fd2e381a5">Aman Bhatia</a>, <a href="https://medium.com/u/782d5a4a6fe5">Imtiaz Jadavji</a>, <a href="https://medium.com/u/ae07f6fa3735">Celine Liu</a>, <a href="https://medium.com/u/91737c79a8c7">Anthony Donohoe</a>, <a href="https://medium.com/u/f1712264dbae">Michael Xian</a>, and Ana Ramdas) as well as the Amplify team.</p><p>If you have any questions about this project, please feel free to reach out to me on <a href="https://www.linkedin.com/in/tylerlanigan/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f5450afb12f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hootsuite-engineering/suggesting-social-media-posts-using-collaborative-filtering-2f5450afb12f">Suggesting Social Media Posts Using Collaborative Filtering</a> was originally published in <a href="https://medium.com/hootsuite-engineering">Hootsuite Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Suggested Reply Feature]]></title>
            <link>https://medium.com/hootsuite-engineering/the-suggested-reply-feature-d35c928324d8?source=rss-f7c2706c2619------2</link>
            <guid isPermaLink="false">https://medium.com/p/d35c928324d8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[hootsuite]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Tyler Lanigan]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 19:13:57 GMT</pubDate>
            <atom:updated>2020-04-27T19:13:57.761Z</atom:updated>
            <content:encoded><![CDATA[<p>The Machine Learning team at Hootsuite released the Suggested Reply to a small number of our customers (~200) on April 8th, 2020. The following details our design process for the system, as well as the final system architecture and preliminary usage metrics.</p><p>The Suggested Reply feature is used in Inbox in Hootsuite. When our customers receive messages from a social network they can respond to them in Inbox. Often, they use the same responses for many messages, and a major pain point that they had was storing and accessing these responses. Customers would use an external tool like Google Docs to accomplish these tasks. This workflow is very awkward so our Engage team build a feature that allows them to save and reuse those messages. But what happens if an organization has 100s of these saved messages? It is really inconvenient to have to scroll down and find the messages that you are looking for each time. Our team decided to augment the Saved Reply feature by using machine learning to sort the list so that the most relevant messages are shown first. Have a look at what this looks like below in Figure 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_BTZJINpODZ3q01s" /><figcaption>Figure 1: Suggested Reply UI Design</figcaption></figure><h3>Final System Architecture</h3><p>The following diagram in Figure 2 shows the flow from start to finish for our Suggested Reply system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*C4EbIvFPheAIcgmtgy7sIw.png" /><figcaption>Figure 2: The Suggested Reply System Architecture</figcaption></figure><p>Let’s walk through what is happening:</p><ul><li>Users select a saved reply on the front end. This causes a CommonResponseSelected event to be emitted on to our local <a href="https://www.confluent.io/download/?utm_medium=sem&amp;utm_source=google&amp;utm_campaign=ch.sem_br.nonbrand_tp.prs_tgt.kafka_mt.xct_rgn.namer_lng.eng_dv.all&amp;utm_term=kafka&amp;creative=&amp;device=c&amp;placement=&amp;gclid=CjwKCAjw-YT1BRAFEiwAd2WRttMAdEDjrpHebHc40uJ2E9FX-VJLW9sHl9xL2_0oEWq5d6cvzB7q7hoCkHIQAvD_BwE">Kakfa</a> based event bus.</li><li>An ingestion service picks this event up, and dumps it into an S3 bucket. This allows us to persist this data and use it for multiple projects. It also allows us to combine it with other data that is present in the data lake.</li><li>A processing service built using Spark’s <a href="https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html">Structured Streaming Engine</a> detects that new data has been added to the data lake. It then processes that data, filtering it and turning it into a form that is more suitable for ingestion into a machine learning algorithm. It dumps that data into a processed bucket. Having a streaming service means that we can retrain the model at any time, as new data is constantly being added to the production folder. It also means that we save a lot of compute time by not reprocessing large batches, essentially duplicating reprocessing work. Using spark allows this processing operation to scale. As this feature is available to all of our customers using Inbox, we expect traffic to increase significantly when Saved Replies is released more broadly.</li><li>The processed folder is then ingested into Sagemaker to train the machine learning algorithm.</li><li>The trained models get saved to S3, where it is easy to revert back to them if something goes wrong in production.</li><li>We load the saved models into an endpoint hosted on Sagemaker infrastructure. This endpoint is exposed to the customer through our GraphQL layer. The GraphQL layer also calls a few other services to fill in the data requirements for our client on the front end.</li></ul><h3>Creating a Labeled Dataset out of Thin Air</h3><p>When we first started this project, we didn’t have any training data coming in because the system had not yet been built. Having an initial set of data is important for experimentation so we can determine if it is possible for the machine learning algorithms to make the predictions that we are asking them to do. In addition it helps with the design of the system, for example do we want to have a two-model system, such as <a href="https://research.google/pubs/pub45189/">Googles’ Smart Reply</a>, or would one model be sufficient? It also helps us answer important experimental questions <a href="https://medium.com/hootsuite-engineering/thresholding-our-smart-social-response-machine-learning-model-340e5abb14f7">like how we want to threshold the model</a>, or how we are going to handle the imbalanced classes.</p><p>Our theory was that we could create our own experimental dataset from our existing data. At this point, we had stored the incoming and outgoing messages for a given organization in our data lake. We just needed a way to figure out which ones were common responses that they used all the time, and which ones were just infrequent one-off answers. We theorized that we could find this using clustering. If we ran a clustering algorithm on the data (e.g <a href="https://towardsdatascience.com/how-dbscan-works-and-why-should-i-use-it-443b4a191c80?gi=a0e56df7f2a6">DBSCAN</a>) answers that are really similar would be clustered in larger groups. We could then look at these groups and then make a judgement if they were template answers. If they were we could assign them a label if they were a certain distance from the centroid of that cluster. The reason that we took this approach was that we found that sometimes answers were templates, but they had small details changed in their final version. E.g the two responses:</p><pre>Thanks Tyler, I hope my service today was helpful and that all your needs were met.</pre><p>is the same response as:</p><pre>Thanks Sam, I hope my service today was helpful and that all your needs were met.</pre><p>With just a name changed.</p><p>So the whole process we used to create our labeled dataset was as follows:</p><ol><li>After performing some initial cleaning steps, we run the data through a clustering algorithm. We used <a href="https://towardsdatascience.com/how-dbscan-works-and-why-should-i-use-it-443b4a191c80?gi=a0e56df7f2a6">DBSCAN</a>, but there are others, such as <a href="https://towardsdatascience.com/k-means-clustering-algorithm-applications-evaluation-methods-and-drawbacks-aa03e644b48a">KMeans</a>. We used the <a href="https://dzone.com/articles/the-levenshtein-algorithm-1">Levenshtein Distance</a> to calculate the distance between points when running DBSCAN.</li><li>Evaluate each cluster using an average <a href="https://github.com/seatgeek/fuzzywuzzy">Fuzz Ratio</a> for distance to the centroid. Clusters that had above a certain score were deemed acceptable for our evaluation.</li><li>Look at each passing cluster and assign it a template. If a cluster had names, tokenize them, for e.g &lt;name&gt;.</li><li>Run through all the data points in a labelled cluster, if they had a certain fuzz score (above 90), automatically assign them the label. If there were below a certain threshold (e.g 70), don’t assign them a label.</li><li>Data points that fell in between these ranges, we hand labelled using <a href="https://aws.amazon.com/sagemaker/groundtruth/">AWS Ground Truth</a>.</li></ol><p>In this manner we only needed to hand label ~5000 data points and ended up with a dataset of over 100,000!</p><h3>BERT vs TFIDF Embeddings</h3><p>With our experimental dataset in hand, we set out to figure out which machine learning techniques would produce the highest accuracy predictions.</p><p>We knew that we wanted our system to have a single model trained for each organization. It wouldn’t be desirable to have one organizations saved replies be recommended for a different organization. With that in mind we knew that our resulting models needed to be small, and thus using a large network for each organization would not have been feasible. Instead, we could take advantage of a large pre-trained model by using it as a general embedding model for everything, then training smaller classification layers for each organization.</p><p>We started by making a baseline model using a simple algorithm. <a href="http://datameetsmedia.com/staging/3908/bag-of-words-tf-idf-explained/">TFIDF</a> features and a logistic regression learning algorithm. We then set out to try and beat it using a more state of the art approach. We chose <a href="https://arxiv.org/abs/1810.04805">BERT</a>, because it was getting some amazing results and there was already wide support from the machine learning community which meant tooling was quickly becoming available.</p><p>The result surprised us. The following in Table 1 details an experiment where we measured the accuracy of each model. A score of 0 represents the model getting none of the answers correct on a held out test set, and a score of 1 means that it correctly labeled all the data points. The models compared are:</p><ul><li>our baseline model — <strong>ta_baseline_model</strong></li><li>BERT embeddings with a logistic regression classifier — <strong>ta_bert_model</strong></li><li>BERT embeddings with a multi-layer perceptron (neural net) classifier — <strong>ta_bert_mlp</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*wnzFRX7-hVAnq_4eRwWHeQ.png" /><figcaption>Table 1: Experimental Results for Baseline Model and BERT</figcaption></figure><p>For our dataset, we did not see a huge improvement using BERT. In fact, in some cases we saw a lower accuracy. This does not mean that with real production data we would not see BERT getting better results, however; with this data-backed evidence and the fact that implementing BERT in production would add another layer of complexity we decided to go with the simpler model for our first version.</p><p><strong>Class Imbalance</strong></p><p>Another issue that we ran into with our first experiments was a severe class imbalance. Most NLP problems suffer from this affliction, where a single class is represented far most than other classes in the data set. <em>I.e</em> A template response is used way more than other template responses. The reason that this is undesirable is, let’s say you have a dataset that has 90% of all the labels as one class, 7% as another, and finally 3% as the last class. A classifier could learn to only predict that over-represented class and get a fairly high accuracy score on a held out test set. In reality, the machine learning algorithm isn’t really doing any predictions based on its input. It’s only ever predicting one class!</p><p>There are many ways to get around this, see this <a href="https://elitedatascience.com/imbalanced-classes">excellent blog post</a> for more details. Our team ended up using down sampling of the majority class, and evaluation using an F1 metric to overcome this problem.</p><p>We also looking into using the <a href="https://machinelearningmastery.com/smote-oversampling-for-imbalanced-classification/">SMOTE algorithm</a>, however the performance costs of this wouldn’t have worked in production.</p><p><strong>Thresholding</strong></p><p>When we deploy this system, we want it to automatically determine if the models should be active for a given organization. My colleague wrote a more detailed blog post on what we ended up implementing. If you are curious, check it out <a href="https://medium.com/hootsuite-engineering/thresholding-our-smart-social-response-machine-learning-model-340e5abb14f7">here.</a></p><h3>Metrics</h3><p>Metrics for our service are displayed in <a href="https://www.interana.com/">Interana</a>. We keep track of the <em>acceptance ratio </em>(how many times our suggestion is accepted divided by how many times it is shown) of our service daily, and get alerted if it ever falls below a certain value. As of now the service is hovering from 50–70%, a number we hope to improve in the future. Figure 3 shows how this metric is tracking daily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/0*VsLsHAJ5xV4x5d6Q" /><figcaption>Figure 3: Acceptance Likelihood for Suggested Reply Predictions</figcaption></figure><h3>Retraining</h3><p>As we have a streaming service constantly streaming new training data into our processed S3 bucket, we can set this training operation to be as often as necessary for our customers. We felt that it was important for the models to be able to predict new saved responses at least the day after they are made, so we set the training cadence to once per day. However, due to using a streaming architecture for the input data, we could theoretically have this operation happen as frequently as the training job can run (currently ~10 minutes). This is a cost-benefit analysis that our team will perform as the feature rolls out to a larger audience.</p><h3>Future Improvements</h3><p>Even though our initial experiments were not promising for BERT, we have not given up on it. Theoretically it should work well, so we would like to perform some experiments using the production data that we have accumulated instead of the labelled dataset that we created. There are some great open source projects out there for using BERT in production such as <a href="https://github.com/hanxiao/bert-as-service">BERT as a service</a> that would make productionizing BERT easy. We envision adding a BERT embedding server (or whatever the current state of art is) into our architecture as follows in Figure 4:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*p8BeFyXh2ytQUa4OYRwjWQ.png" /><figcaption>Figure 2: The Suggested Reply System Architecture</figcaption></figure><p>The BERT server would embed all the data being streamed into the production bucket as well as new data coming in from the front end.</p><p>We would want to test these model differences using Sagemaker’s <a href="https://medium.com/@deepen.h.panchal/a-b-testing-using-aws-sagemaker-boto3-c3dac87ade22">A/B testing capabilities</a> in production.</p><h3>Conclusion</h3><p>I hope that this blog post helps people in their design process for making their own machine learning based systems. The process of building predictive features is far from being standardized and I know that our team has benefited largely from the community putting out details of what they have implemented.</p><p>With that being said I have a list of people I would like to thank my teammates on the Machine Learning Team for working hard to deliver the Suggested Reply project (<a href="https://medium.com/u/347187b8d288">Honto Ming</a>, <a href="https://medium.com/u/51009d035e13">Sam Reh</a>, <a href="https://medium.com/u/4f5b7bcc9b14">Andrew Gormley</a>, <a href="https://medium.com/u/9c4cc5057c5b">MoHan Zhang</a>, <a href="https://medium.com/u/d94fd2e381a5">Aman Bhatia</a>, <a href="https://medium.com/u/782d5a4a6fe5">Imtiaz Jadavji</a>, <a href="https://medium.com/u/ae07f6fa3735">Celine Liu</a>, and <a href="https://medium.com/u/91737c79a8c7">Anthony Donohoe</a>) as well as our Production Operations and Delivery team for helping us set up our infrastructure.</p><p>For more information on our deployment process please refer to our previous blog post on the <a href="https://medium.com/hootsuite-engineering/the-suggested-tags-service-c8dc57d9efe5">Suggested Tag Feature</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d35c928324d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hootsuite-engineering/the-suggested-reply-feature-d35c928324d8">The Suggested Reply Feature</a> was originally published in <a href="https://medium.com/hootsuite-engineering">Hootsuite Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Suggested Tags Service]]></title>
            <link>https://medium.com/hootsuite-engineering/the-suggested-tags-service-c8dc57d9efe5?source=rss-f7c2706c2619------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8dc57d9efe5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Tyler Lanigan]]></dc:creator>
            <pubDate>Tue, 27 Nov 2018 20:02:09 GMT</pubDate>
            <atom:updated>2018-11-27T20:02:09.870Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Hootsuite’s Premier Machine Learning Feature</strong></h4><p>In 2018 Hootsuite took steps to increase our machine learning capabilities for our product by forming a team to deliver the <strong>Suggested Tag Service</strong>. In addition to this feature, our team, along with teams from New York and Bucharest, was tasked with creating a <a href="https://eugdpr.org/">GDPR</a> compliant data lake for machine learning data, and a deployment pipeline template for future ML services. The following is an account of the final system design for this project.</p><p><strong>Motivation</strong></p><p>Hootsuite, as part of its offering, amalgamates all the messages directed through social channels such as Twitter, Facebook and Instagram into one platform. All manners of comment types (reply, posts and private messages) can be seen and responded to, and in addition, Hootsuite also offers an additional functionality: the ability to tag the messages. Tags are used for a variety of purposes by our customers. For example, reports are generated on the semantics of incoming messages (complaints, praise, enquiries). Our team thought it would be possible to suggest these tags given the message content, type, and social network. A suggested tag feature would save our customers time and let them more effectively use tags as we would suggest ones they had used before.</p><p>In addition to providing customer value, our suggested tag feature would serve as a springboard to help us develop the process for deploying ML models at scale for Hootsuite.</p><p>An example of the UX for the Suggested Tags feature is shown in Figure 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7bACndRTx5Jd3GnQHGWsQ.png" /><figcaption>Figure 1: Suggested Tag UX</figcaption></figure><h3>Project Requirements</h3><p>The project began with the following considerations in mind:</p><ul><li><strong>Performance</strong> — The system must be performant in both speed and accuracy of tag predictions. It is serving predictions in real time and must not cause annoying delays in returning predictions. It must also be accurate.</li><li><strong>Scalability</strong> — The system must be able to scale to all our enterprise-level tagging users. This means that we are processing and training on hundreds of GBs of data and serving tens of thousands of suggestions per day.</li><li><strong>Re-training</strong> — Initial analysis of the tagging behavior of our customers showed that new tags are created / archived daily. Our system must be able to pick up these new tags and stop suggesting ones that have been archived.</li><li><strong>Experimentation</strong> — In order to iterate on the design, the system must allow for us to perform experiments without affecting users.</li><li><strong>Model Continuous Integration / Auditability </strong>— Any changes to the code used in the service must be trackable. New models must be able to be swapped in and out of production without affecting traffic.</li><li><strong>GDPR Compliance</strong> — Any data stored must be able to comply with GDPR.</li><li><strong>Roll-back capabilities</strong> — If a new model in production has a bug, there must be the ability to revert back to a previous version quickly.</li><li><strong>Different Environments</strong> — Having local, staging, and production environments allows for development to take place with the least chance of affecting production traffic. Code that is developed in the local environment should work on staging, as well as on production in the same manner.</li></ul><p>An additional criterion for the project was to make it similar as possible to the current workflows for developers at Hootsuite. This way the project could easily be maintained and used as a template.</p><h3>Final System Architecture</h3><p>It is said that you should never reinvent the wheel. We took this proverb to heart as much as possible with this project by utilizing a host of different technologies in our deployment pipeline. The exhaustive list is: <strong><em>Github, Jenkins, Docker, AWS SageMaker, AWS ECR, AWS EMR, AWS Elasticsearch, AWS S3, Spark, SKLearn </em></strong>and<strong><em> Kubernetes. </em></strong>The basic system architecture is as follows in Figure 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8f65EpkhsGxwk5-eihZODQ.png" /><figcaption>Figure 2: Suggested Tags Service System Diagram</figcaption></figure><p>I’ll leave detailed discussion of each of the services until later sections of the post but for now, let’s walk through the main flow:</p><ol><li>Raw data flows from various sources and is deposited into <em>S3 </em>using a service written in <em>Scala</em> and hosted in <em>Kubernetes</em>.</li><li>Metadata (such as date, and data owner) is stored in <em>AWS Elasticsearch</em>.</li><li>A service written in <em>Spark</em> and hosted on <em>AWS EMR </em>is used to process data into a form suitable to be ingested by a machine learning algorithm.</li><li>The processed data is saved in <em>S3</em>.</li><li>At this point, AWS SageMaker spins up a training instance and uses the processed data to produce training artifacts (trained models) and saves them in <em>S3</em>.</li><li>The artifacts are checked for quality then loaded into a serving instance.</li><li>The serving instance receives requests from an inference service that acts as an endpoint for all incoming traffic. Services such as the Hootsuite dashboard will call this service, and it will forward requests to our inference server. The Inferences service acts as a request converter, as well as a way of storing incoming requests and outgoing predictions for future analysis.</li></ol><h3>Data Lake</h3><p>Although the trials and tribulations of storing and processing large amounts of data for this project could fill up an entire post in itself, I’ll just briefly describe our process for preparing data for the machine learning portion of our suggested tags feature.</p><p><strong>S3 Storage</strong></p><p>Data is stored in our S3-based data lake. We ingest data from various sources (such as our event bus powered by <a href="https://kafka.apache.org/">Apache Kafka</a>) and store it in <a href="https://parquet.apache.org/">Parquet</a> format. We initially looked into using <a href="https://www.semantikoz.com/blog/orc-intelligent-big-data-file-format-hadoop-hive/">ORC</a>; but while performance for loading and writing was slightly better with ORC, we decided to use Parquet as it has better support with Python libraries, schemas can be defined using Protobuf, and nested data structures are supported.</p><p>In order to comply with GDPR, we store metadata in Elasticsearch. This allows us to easily find data and delete it if we get a request to do so from any of our customers. We keep data in our raw bucket for 6 months as this was deemed enough for training.</p><p><strong>Spark Processing</strong></p><p>We host and run a Spark processing job on AWS EMR which converts data from our raw bucket into the required form needed for ingestion by the model training service. For a new project, we write new processors that utilize the same raw data. At the beginning of the suggested tag project we wrote a custom Scala job and hosted it in Kubernetes; however, we found that due to the size of the dataset (~500GB) parallel computation was necessary and thus we moved to Spark.</p><h3>The Machine Learning Algorithm</h3><p>To suggest tags for social messages is a <a href="https://en.wikipedia.org/wiki/Multi-label_classification">multi-label</a> machine learning problem. The algorithm that is used to predict tags given message content is based on the paper <a href="https://www.aclweb.org/anthology/P12-2018">Baselines and Bigrams: Simple, Good Sentiment and Topic Classification</a>. We use a modification of this algorithm that used TFIDF vectorization instead of bigram count based features, and logistic regression instead of SVMs. This technique is discussed by Jeremy Howard in his <a href="https://www.fast.ai/about/">fast.ai</a> course for machine learning. We train one of these models for each of the tags (see <a href="https://en.wikipedia.org/wiki/Multiclass_classification#One-vs.-rest">OneVsRest</a> strategy). We then packaged up each of these tag models in a Predictor class for each of our customers as shown in Figure 3 below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*gS2gFRaTDq0XpJ9Y" /><figcaption>Figure 3: Predictor Class Diagram</figcaption></figure><p>Packaging up the models in this manner allows us to write some handy functions around the models. For example, each model is trained, then tested on a held out dataset. It is then scored using the <a href="https://developers.google.com/machine-learning/crash-course/classification/roc-and-auc">AUC</a> value. If the lower bound of a confidence interval on this AUC value (<a href="https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Confidence_Intervals_for_the_Area_Under_an_ROC_Curve.pdf">see Confidence Intervals for the Area Under an ROC Curve</a>) falls below acceptable levels, then we turn off the model. This way, only the tag models that are actually good at prediction are allowed to return predictions in the final system. This threshold was tuned using SageMaker’s handy hyper-parameter tuning capabilities.</p><h3>Training Operation</h3><p>Training machine learning models take quite a bit of computation power and this is what SageMaker is made for! Our current training process uses a <em>ml.m5.4xlarge.</em> To train a model we simply package code up in a Docker image, save it to <em>AWS ECR,</em> point SageMaker to the image and the training data, and specify which resources to use. As we want this process to be accessible to all of our developers, but also auditable and subject to code review, we require that all related code is persisted in Github. After the code is code reviewed and pushed to a master branch, our Jenkins server kicks off the training and deploying jobs. The whole deployment process is shown below in Figure 4:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*Wj9FMsGXeQAsndeV" /><figcaption>Figure 4: Machine Learning Training and Deployment Pipeline</figcaption></figure><p>Our Jenkins server is able to run any of the SageMaker commands that are needed using the AWS CLI commands, or the Python SDK.</p><p>There are many advantages to using this pipeline to perform these training operations:</p><ul><li>Our developers don’t need IAM permissions to spin up and down EC2 instances (as required by SageMaker). Thus any of our developers could deploy a machine learning service. This is a major goal at Hootsuite as <em>we want to enable all our teams to use machine learning as a tool to solve their problems</em></li><li>As training code is stored in images, it is easy to revert back to previous training jobs.</li><li>The pipeline can be run autonomously each day for retraining.</li><li>The developers never have access to <a href="https://searchfinancialsecurity.techtarget.com/definition/personally-identifiable-information">PII data</a> and only look at the results of training operations through aggregate statistics. This is important for compliance with GDPR.</li></ul><h3>Metrics</h3><p>In production we rely on a single guiding metric to let us know how our service is doing: the acceptance rate of the predictions by our customers (i.e how many time are our predictions accepted divided by how many times they are shown). When it comes down to it, this is the most accurate way that we can approximate the true value to our customers!</p><p>However, we do include other metrics at the end of our training run so we can get an idea of the behaviour of the models. As I mentioned before, each of the tagging models is evaluated on a held out validation set, on which we calculate the F2, AUC, Hamming Loss, as well as a host of other metrics. This allows us to get a good idea of the behaviour of the system as a whole.</p><h3>System Monitoring and Detecting Crashes</h3><p>In order to detect when performance is dropping, or when our inference service is not returning predictions, we built dashboards using <a href="https://www.interana.com/">Interana</a>. If our service begins returning errors at an anomalous rate, we are notified in our Slack channel. These steps are important to ensure that we have as little downtime as possible.</p><h3>Retraining</h3><p>Our customers make new tags daily, so our system must be able to retrain daily as well. As deploying each of the necessary jobs (processing data, training models, deploying a new inference server) would be tedious to manually do each day, we created a <a href="https://en.wikipedia.org/wiki/Cron">Cron job</a> in Jenkins that will run each step for us. To ensure that we don’t deploy poor models, we write model quality and integration tests that will stop that deployment if something is wrong. This way we can be hands-off, and only get notified if there is an error.</p><h3>The Final Balancing Act and Performance</h3><p>After an extensive beta trial with a select group of customers, we were able to decide on a final design for our suggested tagging system. As each prediction model for our customers returns a probability for each tag that they use, we only suggest tags to our customers that are above a certain threshold. Thus, sometimes our service does not return <em>any</em> tags for a given message, or returns fewer than our default amount of three. In these cases, we fill in the blanks with the most recently used tag, creating a hybrid system.</p><p>In order to validate our machine learning service, we conducted an A/B test where we presented half of our beta cohort with the most recently used tag as a suggestion, and half with our machine learning prediction. While the machine learning system performed better than then recent tag system, we found that the hybrid system performed even better than the machine learning, or recently used tag systems alone.</p><p>Our performance varies slightly day-to-day, however, we consistently have an acceptance rate of 60–65%.</p><h3>Conclusion</h3><p>Building a production level machine learning systems is not easy. Luckily the tools that are available to help are becoming more prevalent day by day. Keep a lookout in the future for more projects from Hootsuite’s Machine Learning Team. If you have any questions about this project, please feel free to reach out to me on LinkedIn: <a href="https://www.linkedin.com/in/tylerlanigan/">https://www.linkedin.com/in/tylerlanigan/</a>.</p><p>I’d like to thank <a href="https://medium.com/u/ce80545be805">Jonathan Meyers</a> from our New York Office, Ethan Aubuchon from our Toronto office, and the Bucharest and Vancouver Ops teams for their help with designing and building the data lake. Shoutouts to my teammates <a href="https://medium.com/u/347187b8d288">Honto Ming</a>, <a href="https://medium.com/u/51009d035e13">Sam Reh</a>, and <a href="https://medium.com/u/4f5b7bcc9b14">Andrew Gormley</a> for being generally awesome and working hard to deliver the suggested tag project with me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8dc57d9efe5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hootsuite-engineering/the-suggested-tags-service-c8dc57d9efe5">The Suggested Tags Service</a> was originally published in <a href="https://medium.com/hootsuite-engineering">Hootsuite Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>