<?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[Fun with data and stats - Medium]]></title>
        <description><![CDATA[Exploring the data around us for mostly fun and not so much profit - Medium]]></description>
        <link>https://medium.com/fun-with-data-and-stats?source=rss----b07a190ff69d---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Fun with data and stats - Medium</title>
            <link>https://medium.com/fun-with-data-and-stats?source=rss----b07a190ff69d---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:06:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/fun-with-data-and-stats" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Predicting the ambiance of restaurants using only the wording of Yelp reviews]]></title>
            <link>https://medium.com/fun-with-data-and-stats/predicting-the-ambiance-of-restaurants-using-only-the-wording-of-yelp-reviews-954413b6d490?source=rss----b07a190ff69d---4</link>
            <guid isPermaLink="false">https://medium.com/p/954413b6d490</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Steven Tang]]></dc:creator>
            <pubDate>Thu, 23 Mar 2017 01:37:08 GMT</pubDate>
            <atom:updated>2017-03-22T22:33:26.124Z</atom:updated>
            <content:encoded><![CDATA[<p>Businesses on Yelp are often tagged with certain attributes to help users better understand what to expect when walking into a restaurant or other establishment. Reviewers help Yelp tag the business in their reviews. That led me to wonder whether these manually tagged attributes of a restaurant could be inferred by the text of the reviews themselves, since both reflect the same reviewers’ opinions. If this is possible, then Yelp could conceivably predict things about restaurants that users haven’t tagged yet, or perhaps provide suggestions to reviewers.</p><p>To answer this question, I used data from the <a href="https://www.yelp.com/dataset_challenge">Yelp Dataset Challenge</a>.</p><h4>Framing the Problem</h4><p>There are tons of attributes that Yelp stores about businesses. I’m going to consider only the “Ambience” and the “Good For” attributes of businesses that are categorized as Restaurant, Food, or Nightlife. “Ambience” can take on values of [Divey , Hipster, Casual, Touristy, Trendy, Intimate, Romantic, Classy, Upscale], and “Good For” can take on values of [Breakfast, Brunch, Lunch, Dinner, Late Night, Dessert].</p><p>Yelp’s “Ambience” and “Good For” attributes share an important trait: users can check off a business to have multiple values of each attribute. A restaurant can be both “Hipster” and “Casual”, and it might be good for both “Lunch” and “Dinner”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*r88Ssr6W-bRcRF2eG16ahw.png" /><figcaption>A sample of the options presented to Yelp reviewers</figcaption></figure><p>So now we can state our problem: using the text of the reviews of for a business, predict which labels from the “Ambience” and “Good For” attributes this business should have.</p><h4>Using words to perform classification</h4><p>Our crucial idea here is that people probably say similar things about restaurants that share an “Ambience” or a “Good For”. Perhaps a business is more likely to have a set of labels if its reviews are similar to the reviews of other businesses who share the same labels.</p><p>How do we know when reviews are similar? I decided to use an approach called <a href="https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm">k-nearest neighbors</a>. The idea is that an unlabeled instance can be classified by observing the the labeled instances closest to it, that is, its nearest neighbors. The diagram below demonstrates a simple implementation of the algorithm to classify the unknown red star. If we look at its 3 closest neighbors, the unknown instance is most similar to a blue hexagon since a majority of its neighbors are hexagons; comparing it to 5 neighbors may lead us to believe that it’s a green square.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8UeMSRLTQTM_LLhCBRCew.png" /></figure><p>To formulate a definition of nearness between Yelp reviews, we need to answer two questions:</p><ol><li>How do we assign a quantitative value to text data?</li><li>What metric do we use as a distance between our quantitative representations of texts?</li></ol><h4><strong>Definitions</strong></h4><p><strong>Document:</strong> a body of text that we’d like to compare to other bodies of text. For our model, I combined all of a single business’ Yelp reviews into one large review. This way, comparing one document to another is equivalent to comparing businesses to one another.</p><p><strong>Corpus:</strong> the collection of all documents in our analysis. For our model, the corpus is our set of Yelp businesses.</p><p><strong>Term:</strong> a unique word in a document.</p><h4>Vectorizing reviews</h4><p>Before we can measure the distance between reviews, we need to turn them into quantitative values upon which we can apply a distance function. There are many ways do this with text data. We’re going to use an approach that transforms reviews into a collection of terms and gives each term a score.</p><p>Instead of simple term count, we’ll assign a statistic called <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf">tf-idf</a> to each term in our review. Tf-idf measures the importance of a term to a document by multiplying <em>term frequency (tf) </em>with <em>inverse document frequency (idf)</em>, which measures the rarity of the term across our entire corpus.</p><p>As a result, we assign a higher score to rare words that may be more important to determining the meaning of the document. In the context of Yelp reviews, it makes sense that we’d want to assign the term “burrito” a higher score than the term “eat”, even though the frequency of “eat” is much higher.</p><p>We can calculate the tf-idf score for each term in our document, giving us a collection of scores that we can turn into a <em>T</em>-dimensional vector, where <em>T</em> is the number of terms in our document. We’ve transformed our document into a quantitative representation that allows us to measure distance between documents.</p><h4>Distance between document vectors</h4><p>We’ll measure distance by using a metric called <a href="https://en.wikipedia.org/wiki/Cosine_similarity">cosine similarity</a>, which is the cosine of the angle between our review vectors. For our purposes, the angle between vectors is a good measure of document similarity since the direction that the vectors point in matters more than their magnitude. For instance, document A should be perfectly similar to document B if document B is simply two concatenated copies of document A. We’re going to normalize our term frequencies so the magnitude issue won’t apply here, but we may want to calculate term frequency another way for other analyses. Perfectly similar documents will have a similarity of 1 and opposite documents will have a similarity of 0. This will be our distance metric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*lEoHSo_bqgC_-NXhyUn9LA.png" /><figcaption>Similarity between document A and document B can be calculated using the dot product (Wikipedia)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*MS-3nyrL89pRBaumsAWacg.png" /><figcaption>cos(𝛳) is the similarity between review vectors</figcaption></figure><h4>Predicting labels with nearest neighbors</h4><p>With our quantified reviews and distance function in hand, we’re ready to find a document’s nearest neighbors. We combine our document vectors into a <em>m </em>x<em> n</em> <a href="https://en.wikipedia.org/wiki/Document-term_matrix">document-term matrix</a> containing our tf-idf scores, where each row of the matrix represents a single labeled document and each column represents a term. The unlabeled document can similarly be represented as a <em>n </em>x<em> 1 </em>vector of its tf-idf scores. Taking the cosine similarity of these matrices allows us to compute a <em>m </em>x<em> 1</em> similarity matrix of our unlabeled document with all of our <em>m </em>labeled documents. The labeled documents with the highest similarity scores are the unlabeled document’s nearest neighbors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*ouGsAzjTYgriFG8ppoerKg.png" /></figure><p>Now that we can find our nearest neighbors, we can use that information to figure out which labels to apply to our unlabeled business. If we‘re observing our 5 nearest neighbors and find that 3 of them are “Casual”, 2 of them are “Lunch”, and 1 of them is “Upscale”, how do we turn that into a prediction for the label set of our unlabeled instance?</p><p>Essentially, we will give our unlabeled document a label if the probability of having the label is greater than the probability of not having the label, and vice versa. To calculate these probabilities, we need to know (1) the prevalence of the label in our data (over 2/3 of businesses are labeled “Casual” while only about 1/65 are labeled “Upscale”) and (2) how likely it is that the unlabeled instance has a certain number of neighbors with a certain label, given it actually has that label (it’s much more meaningful when we see that some of our neighbors have the “Upscale” label than when we see that our neighbors have the “Casual” label).</p><p>Once we have these probabilities, we‘re ready to make predictions for the labels of an unlabeled Yelp business.</p><p>For more details on this model, see the appendix.</p><h4>Model selection and evaluation</h4><p>We have one more question to answer: how many neighbors <em>K</em> should we take into account in our model? We’d like to select the model that minimizes some error function(s). To do this, we’ll split our data into training/test sets and use 10-fold <a href="https://en.wikipedia.org/wiki/Cross-validation_(statistics)">cross-validation</a> to test different values of <em>K.</em></p><p>There are a few error metrics we can consider for multi-label predictions. We’ll evaluate hamming loss (the rate at which we misclassify labels), coverage, one-error, and average precision (measurements of how well can rank our label predictions based on our calculated probabilities). For more details on the error metrics, see the appendix.</p><p>Depending on the goal of our model, we may want to optimize for a different error type. With model selection and cross-validation, we have all the pieces of our model. It’s time to apply it to actual data.</p><h4>Methodology</h4><p>I used R to clean up the data and <a href="https://github.com/steventang/yelp-knn-labels">write</a> the functions to build the model.</p><p>Preprocessing leaves us with and 15,474 businesses and 2,834 terms as model features.</p><p>For more on the methodology, see the appendix.</p><h4>Results</h4><p>To put our results into context, it’s helpful to visualize our label distributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*E6vpEVtQAx1p2TpY96-gmA.png" /></figure><p>Across our 15,474 businesses, we have a total of 37,970 labels, giving us 2.4538 labels per business on average.</p><p>How do we know whether our results are any good? We should compare our model to classifiers we could create without any model. The “Casual” label is most common with 10,777 instances. We could build a naive classifier that classifies all instances as having only the “Casual” label. Since over half of our observations have “Lunch” and “Dinner” labels, we can also tell our naive classifier to label every instance with these two labels. This naive classifier produces a hamming loss of 0.1195. We can also create a naive function that ranks our labels for each review only by their prior probability (i.e., as they’re ordered in the chart above). This naive ranking gives us a coverage of 4.8143, a one-error of 0.3035, and an average precision of 0.7414. The errors produced by our no-model naive classifiers serve as benchmarks to test the performance of our model.</p><p>Let’s take a look at the top features in our model, that is, the terms in our document-term matrix that have the largest tf-idf scores summed over all of our documents. These features are ostensibly the most meaningful in our corpus of reviews. The raw counts of terms in our corpus are shown alongside in the table below for comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*NAkCgEWSdu-KB51eBAaV7A.png" /></figure><p>We can throw together some word clouds to get a bigger picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*Oh8dlaP0yFHofhzgcdwDKQ.png" /></figure><p>Words with high tf-idf scores are largely specific types of food (e.g. taco, bagel, lobster), while the terms with the largest raw count are more generic words that could apply to any business. If our model has predictive power, then this suggests that the type of food written about in the reviews give us insight into the ambience of the business and what meal service types its good for.</p><p>The top tf-idf scored features of businesses with the “Breakfast” and “Dinner” labels look quite different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*wyBCTKILfanbWfCgNBXG8Q.png" /></figure><p>We train models on all values of <em>K</em> from 1 to 30 and compute errors to pick the best <em>K</em>. The smallest cross-validated errors are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*eNiMhOQ-sJGO4ZFOJLpwxw.png" /></figure><p>Good news — our model has more predictive power than our naive classifiers in every error metric.<em> K </em>= 13 gives us our minimal hamming loss of 0.08184, a 31.51% reduction in misclassifications over our naive classifier. These results show that the words used in Yelp reviews do encode information about the attributes of businesses. Our Yelp Elite friends are conveying more information about a restaurant than perhaps they even realize.</p><p>We can see that our error rates become asymptotic as we increase the number of neighbors considered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Sg6Cjzma18Tb5ayPL2kjMg.png" /><figcaption>Our naive classifier benchmark hamming error is 0.1195</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*hzY30sSodxx-zWuKfiwYZw.png" /><figcaption>Our naive classifier benchmark average precision is 0.7414</figcaption></figure><p>We can now pick <em>K</em> for our model based on which error type we’d like to minimize.</p><h4>Predicting San Francisco</h4><p>Let’s try applying our model to predict the labels for some of San Francisco’s famed establishments: <a href="https://www.yelp.com/biz/gary-danko-san-francisco">Gary Danko</a> (“Classy”, “Upscale”, “Dinner”), <a href="https://www.yelp.com/biz/straw-san-francisco">Straw</a> (“Hipster”, “Casual”, “Dinner”), <a href="https://www.yelp.com/biz/taqueria-canc%C3%BAn-san-francisco-5">Taqueria Cancun</a> (“Casual”, “Lunch”, “Dinner”, “Late Night”), <a href="https://www.yelp.com/biz/tommys-joynt-san-francisco">Tommy’s Joynt</a> (“Casual”, “Lunch”, “Dinner”), and <a href="https://www.yelp.com/biz/li-po-cocktail-lounge-san-francisco">Lipo Cocktail Lounge</a> (“Divey”). Note our model wasn’t trained on any businesses from SF.</p><p>I scraped all the reviews for these businesses from Yelp’s website (fun fact: the cumulative word count of Gary Danko’s reviews is over 800,000, making it longer than the Bible) and applied our 13-neighbor model to each restaurant’s reviews. Here’s what we predict:</p><p><strong>Gary Danko: “Dinner”</strong>. We missed out on the rare “Classy” and “Upscale” labels, but we assigned them pretty high probabilities relative to other labels at 41.43% (compared to 3.5% prior probability) and 22.98% (1.5% prior) respectively. “Romantic” had a 29.93% chance, and everything else had less than 6% chance. It’s worth noting that we did well in assigning “Casual” only a 5.05% chance (69.64% prior).</p><p><strong>Straw: “Casual”, “Lunch”, “Breakfast”</strong>. “Hipster” is a rare label that’s tough to predict — we weren’t even close, assigning it a 1% chance. I actually think we assigned “Breakfast” and “Lunch” correctly here, since Straw is best known for its brunch service. In this case, we seem to have predicted more appropriate labels than the “Good For” shown on Yelp. The model felt strongly about “Breakfast” at 77.96% chance (13.02% prior) and weakly about “Dinner” with 25.33% chance (53.82% prior). A probability-based model like this could be useful to catch errors.</p><p><strong>Taqueria Cancun: “Casual”, “Lunch”</strong>. We missed the most interesting label, “Late Night”, though we went in the right direction, assigning it 27.15% probability (8.9% prior).</p><p><strong>Lipo Cocktail Lounge: “Casual”, “Lunch”, “Dinner”</strong>. This was just completely wrong, and I think I know why. The top term of Chinatown icon Lipo Cocktail Lounge is “Chinese”, which is overwhelmingly associated with casual Chinese food places. Our model had no chance.</p><p><strong>Tommy’s: “Casual”, “Dinner”, “Lunch”</strong>. We got all the labels correct here, and that’s partly because we predicted the most common labels.</p><h4>Shortcomings</h4><p>Let’s take a closer look at a how our model can go wrong:</p><p>The Wine Mill in Peninsula, OH has been labeled “Trendy” and “Romantic” by Yelp users, but our model thought it was only “Casual”. A sample of the reviews:</p><pre>Great little find in Peninsula! Amazing atmosphere inside and out - they really spent time with the decor! The staff was very nice and the (I think) own stopped by our table to say hi. We ordered 3 different dips (chicken, artichoke, and crab) and the cheese board. We also had the house cab and Pinot...</pre><pre>The Wine Mill offers 2 house made wines within each category. They have a great size wine list for a small neighborhood establishment. They offer a great mix of sweet and dry wines. You can get most wines as a Taste, Glass or Bottle...</pre><p>The top 5 features for this business are “wine”, “slider”, “mill”, “jar”, and “artichok”. Strangely enough, “wine” isn’t in the top 100 features of businesses labeled “Romantic” or “Trendy”, while it is in the top 100 features of “Casual”. We don’t have many data points for “Romantic” and “Trendy” businesses, so we may simply not have encountered enough reviews that talked about wine. For the rarer labels like “Romantic”, we really need more data to predict it accurately. Furthermore, our model can’t understand that this is a trendy wine bar rather than just another restaurant that serves wine. If we had taken into account sequences of words instead of just looking at single words, perhaps terms like “wine list” or “house made wines” may have helped us make more accurate predictions.</p><p>We can improve our model in several areas:</p><p><strong>Feature engineering</strong> — we did not perform much feature engineering beyond tf-idf scoring our reviews, word stemming, and removing sparse terms. We could try other things to extract more predictive features out of our bodies of text. <a href="https://en.wikipedia.org/wiki/Word2vec">Word2Vec</a> might be an document vectorization technique to explore. We could try using n-grams, sequences of words, to add more meaning-rich features. Furthermore, we didn’t test whether the feature engineering we did perform actually improves or degrades model performance.</p><p><strong>Imbalanced data</strong> — the label distribution of the data is imbalanced, heavily favoring the top 3 labels. Some of our labels are pretty rare, which makes training the model more difficult for those labels. If we had more balanced labeled examples, the model would learn better.</p><p><strong>Validation set sampling </strong>— we sampled our cross validation sets uniformly, which may cause our CV splits to contain imbalanced proportion of labels in relation to our total dataset. Normally we’d like to use stratified sampling to generate representative folds of training/test splits, but it doesn’t make much sense when we have multi-label data. There have been more complicated techniques proposed to sample multi-label data for cross-validation, but for purposes of simplicity, I just use standard cross-validation here. Our error rates may be off as a result.</p><p>You can take a look at the code used for this analysis <a href="https://github.com/steventang/yelp-knn-labels">here</a></p><h4>Appendix — Multi-label KNN algorithm</h4><p>K-nearest neighbors is commonly used for binary classification problems in which we classify an unknown instance into a single class. To extend the technique to a multi-label classification in which the unknown can simultaneously belong to any number of classes, we estimate probabilities for each label by finding the prior probabilities of each label and the posterior probabilities of observing certain numbers of our neighbors having each label. We give our unlabeled document a label if the probability of having the label is greater than the probability of not having the label, and vice versa.</p><p>We use a Bayesian technique that makes use of a <a href="https://en.wikipedia.org/wiki/Maximum_a_posteriori_estimation">maximum a posteriori estimator</a> put forth by <a href="http://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/pr07.pdf">this paper</a> to calculate the probabilities for each label.</p><p>Suppose we have an unlabeled test document<em> t </em>and a set of labels <em>𝒴</em>. Let <em>C(l) </em>be a function that counts how many neighbors of<em> t </em>have a label<em> l, l∈𝒴. </em>Let <em>H(1, l) </em>denote the event that<em> t </em>has label <em>l </em>and <em>H(0, l)</em> be the event that t does not have label <em>l</em>. Let <em>E(j, l) (j ∈ {0, 1, . . . , K})</em> denote the event that, among the <em>K</em> nearest neighbors of <em>t</em>, there are exactly <em>j </em>instances which have label <em>l. </em>Let <em>y(l)</em> be an indicator function that takes on a value of 1 if <em>t</em> has label <em>l</em> and 0 otherwise.</p><p>Then the label vector for our test document <em>t</em> is the arg max of (the conditional probability of <em>t</em> having label <em>l, </em>given exactly <em>C(l)</em> of its neighbors have label <em>l) </em>and<em> (</em>the<em> </em>conditional probability of <em>t</em> not having label <em>l, </em>given exactly <em>C(l)</em> of its neighbors have label <em>l)</em> for all <em>l∈𝒴</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*WqHJ8PO-iKSLgLW8rr7jxQ.png" /></figure><p>We can compute this conditional probability by using Bayes’ rule to transform the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*z4qRIjGRbuwQVWXbQTVAXw.png" /></figure><p>Now our problem is reduced to finding the priors <em>P(H(b, l)), (l ∈ 𝒴, b ∈ {0,1}) </em>and the posteriors <em>P(E(j,l)|H(b,l)), (j ∈ {0, 1, . . . , K}). </em>The priors can be calculated simply by dividing the number of documents with label <em>l</em> by the total number of documents. I implemented the algorithm described in the paper to calculate the posterior probabilities. The information gain in our model is embedded in the posteriors of observing our neighbors having labels. Note that these probabilities are calculated using our training set, the set of documents that are already labeled.</p><p>So for each unlabeled test instance <em>t</em>, we can now compute a vector of length ‖<em>𝒴</em>‖ that takes values 1 if <em>t</em> is predicted to have label <em>l ∈ 𝒴 </em>and 0 otherwise.</p><h4>Appendix — Multi-label error metrics</h4><p><strong>Hamming loss</strong> measures the percentage of labels that are misclassified. It’s a good measure of overall model performance. Hamming loss ranges from 0 to 1 and we want it to be small, optimally 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*ldntuPYP3grePEC8b7f4Fg.png" /></figure><p>where <em>p</em> is the size of our test set, <em>Q</em> is the size of our label set, <em>h(·)</em> is our multi-label classifier predictor, <em>Y</em> is the true set of labels, and 𝚫 denotes symmetric difference of sets.</p><p>Our model also allows us to construct a ranked set of labels in which labels with a larger probability of occurring <em>P(H(1,l) | E(j,l)) </em>outrank those with a lower one. Let <em>f(·)</em> be the function that outputs these probabilities and <em>rank(·)</em> be the function that outputs the actual ranked position of a label.</p><p><strong>Coverage</strong> tells us how far we have to go down the ranked list of labels before find all the true labels for our instance. It’s useful to measure when we want to get all the labels correct, even at the expense of some false positives. We want coverage to be small. The optimal coverage is the average number of labels per instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*q0f41uOOq5OC9vBmxif7rw.png" /></figure><p><strong>One-error </strong>is the rate at which the top-ranked predicted label is not in the set of true labels for our instance. It may be especially important if we want to have high confidence that one label prediction is correct. It ranges from 0 to 1 and we want one-error to be small, optimally 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*W_OwRD_Xg2MQ04RikEqT2g.png" /></figure><p>where ⟦<em>E</em>⟧ is an indicator function that takes on 1 if <em>E</em> is true and 0 otherwise.</p><p><strong>Average Precision</strong> is a metric that evaluates document ranking performance. For each true label, average precision measures the fraction of true labels that are ranked before it. It ranges from 0 to 1, and we want it to be closer to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*tinM32H6La71nwfC83i4jw.png" /></figure><h4>Appendix — Methodology</h4><p>I used R to clean up the data and <a href="https://github.com/steventang/yelp-knn-labels">write</a> the functions to build the model. Since we may have to hold 10’s of GBs of data objects in memory, I ran R on AWS EC2 instances. It’s pretty <a href="https://aws.amazon.com/blogs/big-data/running-r-on-aws/">straightforward to install</a> the RStudio on EC2 and ssh the dataset onto our instances. I forgot that R doesn’t natively support parallel processing and I didn’t want to rewrite my code, so I opted to train the model simultaneously on multiple EC2 instances. Since I couldn’t make use of more processing power, I chose the r4.xlarge instance to optimize for memory.</p><p>The Yelp dataset contains 4.1M reviews and 86K businesses. To read in Yelp’s json data and turn it into an R data frame object, I used R’s jsonlite package. I combined all the reviews for a single business into a single document. This way, each business can be considered a single document and the collection of our businesses is our corpus. To ensure our documents have reasonable length, I removed all business that have fewer than 20 reviews. This pre-processing leaves us with a total of 15,474 documents in our corpus.</p><p>Using the quanteda package, I created a document-term matrix and removed <a href="https://en.wikipedia.org/wiki/Stop_words">stop words</a> , performed <a href="https://en.wikipedia.org/wiki/Stemming">stemming</a> so that we only consider root words to be unique, and removed terms beyond a certain threshold of <a href="https://en.wikipedia.org/wiki/Sparse_matrix">sparsity</a> until we are left with 2,834 terms as model features.</p><p>For each cross-validation split, I trained our model on the training set , then compute a cosine similarity matrix on the test set. This matrix will give us our nearest neighbors (from our training set) for each document in the test set. Then for each label, we calculate the probability of the document having or not having the label using our priors and posteriors for that particular label and value of <em>K. </em>We generate predictions like this for each value of <em>K </em>that we’d like to test, then average the errors for each CV fold to arrive at the error values for each <em>K.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=954413b6d490" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fun-with-data-and-stats/predicting-the-ambiance-of-restaurants-using-only-the-wording-of-yelp-reviews-954413b6d490">Predicting the ambiance of restaurants using only the wording of Yelp reviews</a> was originally published in <a href="https://medium.com/fun-with-data-and-stats">Fun with data and stats</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drafting a Fantasy Basketball Team With Help From Statistics and a Knapsack]]></title>
            <link>https://medium.com/fun-with-data-and-stats/drafting-a-fantasy-basketball-team-c94967464908?source=rss----b07a190ff69d---4</link>
            <guid isPermaLink="false">https://medium.com/p/c94967464908</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[basketball]]></category>
            <dc:creator><![CDATA[Steven Tang]]></dc:creator>
            <pubDate>Wed, 27 Jan 2016 20:36:06 GMT</pubDate>
            <atom:updated>2016-01-27T20:37:46.615Z</atom:updated>
            <content:encoded><![CDATA[<p><em>You can find the accompanying draft optimization tool </em><a href="http://fantasy-ballsack.herokuapp.com/"><em>here</em></a></p><p>How does one draft the best possible fantasy basketball team? I like to think of this as a statistics and optimization problem rather than a sports knowledge problem (though knowledge only helps).</p><p>In this post I’ll present an approach to drafting an optimal team in a weekly H2H 9-cat league, an approach that I’ll be testing for my upcoming draft. This strategy by no means solves the problem holistically (in fact it’s far from complete), nor can I claim that it performs significantly better than any other approach, qualitative or quantitative. It’s just one that I find interesting and somewhat sensible, a thought experiment if you will.</p><p>For those unfamiliar with the rules of fantasy basketball, refer to the appendix below or to the notes on the right.</p><h4>Setting the scene</h4><p><strong>Projection data</strong> —any draft strategy necessitates that we have some notion of players’ values. I’ll rely on third-party projections of players’ stats for the coming 2014–15 season since such projects generally perform well. In this case I’ll use <a href="http://fantasynews.cbssports.com/fantasybasketball/rankings">CBS’s projections</a> as an example. Our first difficult task is to determine how to value a player given their known season performance in the 9 categories.</p><p><strong>Single-number value</strong> — a player’s overall value must come from some extrapolation of the player’s 9 stat categories. To create a simple basis for comparison, I want to distill each player’s value down to a single number that represents his relative value vs. others. And I want to do this so that I not only have an idea of the ranking of players, but also a good idea of the magnitude of difference in value between them.</p><p><strong>Scope of the draft pool</strong> — we don’t want to compare players to the entire pool of NBA players since we really only want to get an idea of relative value within the group of players that are most likely to get drafted. In a 16 person league, 203 players will be drafted, so I’m going to choose the feasible draft pool to be 250 players — CBS’s top 50 centers, top 100 guards, and top 100 forwards. Also note that I’ll be comparing projected season totals, which take into account, for example, that Kevin Durant will likely miss around 15 games from his current injury.</p><h4>A valuation approach</h4><p>Summing a player’s absolute stats obviously has no meaning. Instead, I want to draft players who are as above average as possible. At this point, it’s informative to examine frequency distributions for each of the 9 stats across our feasible draft pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*DZJgpDRZBc_eVa4soyw3ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*zsBjFPmG9TRz_eSDx4lSmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*_tNuFx0Kv_o25H7BKF4j7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*swNbPWXFdxFUZFspaAWwcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*_7tOlb2sHM5N_yBYJvIlDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*neo0j5dPuDrCrJNWegexbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*tvqzBvUkSTkSIuSVmwUPpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*SiP5U1iqtoTTxrTAD_ujLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*REHimo3syq2upshcjr0h2g.png" /></figure><p>One thing to note — these stats are not normally distributed. Extreme outliers are present but infrequent. Because our distributions vary so widely, we need to normalize our data for comparison to be possible.</p><p>How do we measure how far away a player is from average? For this analysis, I’ll simply use a player’s standard deviations above the mean. This will give us a player’s score for each category (<em>z</em>), which we’ll calculate like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/86/1*L9O4e5Hld8SMZf6DgXMAyg.png" /></figure><p>where <em>x</em> is the player’s projected total, <em>µ</em> is the mean of our feasible draft pool, and <em>σ </em>is the standard deviation.</p><p>In fact, this <a href="http://en.wikipedia.org/wiki/Standard_score">z-score</a> (standard score) is commonly used to normalize data when comparing data from multiple variables. Normalization gives us an additional benefit — we can sum a single player’s z-scores for each of the 9 categories without allowing a single category with a large variance to dominate the sum. Consequently, we’ve arrived at our method for distilling player values into a single number: calculate a player’s z-score for each stat category, then take their sum, giving us his total standard deviations away from the mean as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*msjOYs8orbO5wjNTlcAjhQ.png" /></figure><p>Here are mean and standard deviation data for the 250 players in our pool:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*9dGJOYtStoVf_me7bignEw.png" /></figure><h4>Valuation results</h4><p>Calculating player values using the z-score method, we get a resulting value for each player. The full results are in <a href="https://docs.google.com/spreadsheets/d/1JC8NoThIJhd420NpLeLn1VJpNJ4gfCDQN-rJu228m9I/edit?usp=sharing">this Google Doc</a>. Here are the players with the 50 highest scores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*PK-n85IgBVr5T3hodEHtPQ.png" /></figure><p>Some observations — Russell Westbrook is at 34, which is almost certainly too low, and Eric Bledsoe at 93 is almost worse; John Wall seems low at 15; DeAndre Jordan stands at 5, which is too optimistic; Kyle Korver at 24 and Robin Lopez at 39 are too high. But these values are unsurprising for the most part, giving us a bit of confidence that we’re on the right track.</p><p>Looking at a distribution of scores makes it clear just how much better the top players are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*i4C35rKjNCfUP7R9n-U9qQ.png" /></figure><p>Observe that we also have a measure of the magnitude of value differences between players. #1 Lebron James is almost twice as valuable as #22 Paul Millsap. That is, Lebron should be getting us points totals that are twice as many standard deviations above the mean than Millsap.</p><p>By studying DeAndre Jordan’s stats, we can understand why he received such a high score. He is <em>the</em> most extreme outlier in both categories, and more extreme of an outlier than outliers in other categories (he also happens to top the rebounds category). He scores greater than 4 deviations above the mean in blk and FG%; every other category only contains scores under 4. But since we’re attempting to filter for extraordinary players, it’s not imprudent to score outliers highly. Note that we make no value judgements about the merits of dominating a small number of categories in comparison to showing strength in a large number of categories. In practice, a draft strategy would take this difference into account.</p><p>DeAndre Jordan’s strength here may also be due to overly optimistic projections by CBS, which has him throwing down 2.62 blk/game and 13.44 reb/game compared to ESPN’s projections of 2.1blk/game and 11.2 reb/game. This shows the importance of our input data. We’ve assumed that our projections are population data. We can improve on this by sampling projections from a broader range of sources, then take into account standard error when doing calculations.</p><h4>Solving the Knapsack Problem for draft picks</h4><p>With a list of player values at our disposal, we’re now in a position to create a methodology for our draft. Snake style drafts can be trivially solved by selecting the highest value player with every pick, so I’ll focus on auction-style drafts.</p><p>We can frame the auction draft problem like this: given a list of players with corresponding values, and given a price that each player will <em>likely </em>go for, how do we pick players such that we maximize our total team value? Using these prices as a starting point, we can solve this problem with updated bid prices during the actual draft to find our new optimal team. This means that we’ve arrived at our final problem:</p><p><strong>Given a set of players, each having a price and value, pick at most N players such that we maximize the sum of player values and the sum of the player prices is less than our budget B.</strong></p><p>It turns out that this problem is identical to a well-known optimization problem, the <a href="http://en.wikipedia.org/wiki/Knapsack_problem">Knapsack Problem</a>. How fortunate! It states: given a set of items, each having a value and weight, pick items to put in a knapsack that maximize value given a weight constraint. The 0–1 knapsack problem restricts the copies of each item to either 0 or 1. Fantasy drafting can be modeled as a 0–1 knapsack problem with one additional constraint: the total of items (players) cannot exceed the max team size. Note that the optimal picks for a team size of at most N is the same as the optimal picks for a team size of exactly N, since the remainder of the team can be filled with 0 bid players.</p><p>The knapsack problem must be solved algorithmically. I used a modified version of the dynamic programming solution from <a href="http://rosettacode.org/wiki/Knapsack_problem/0-1#Ruby">Rosetta Code</a>.</p><p>The last piece is a list of likely player prices. For this, I used Yahoo’s auction draft prices averaged from drafts thus far this season.</p><p>Here are the results with our values calculated above and a budget of 200 with a max team size of 13:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*7SlD_XDM5qwh-eS2if4ntg.png" /></figure><p>To help you solve your own knapsack problems, I’ve made an app that does the calculations for you: <a href="http://fantasy-ballsack.herokuapp.com/">http://fantasy-ballsack.herokuapp.com/</a></p><p>That’s it! This is the optimal lineup produced by our z-score/knapsack methodology. Of course, these are not the actual players you should bid for. The solution changes with every new piece of player price information. In the beginning of the draft, if Lebron is bid at $20, the knapsack algorithm will choose Lebron to be on your team, given that each other player’s price is set to their <em>likely</em> price by default.</p><h4>Shortcomings</h4><p><strong>We don’t take player positions into account </strong>— we can’t draft a team with all centers. Fantasy matchups mandate that certain certain player positions are filled. Basketball’s positions are flexible enough where we can get away with this level of analysis, but a deep analysis should take this into account.</p><p><strong>Percentage categories don’t take number of attempts into account — </strong>a player may have a FG% of 100% during the week’s matchup, but that hardly helps if he’s made 1/1 field goals that week. Our analysis gives too much credit to players who have high percentages but low number of attempts, and vice versa.</p><p><strong>Category saturation isn’t accounted for </strong>— this method maximizes total player z-scores, but those deviations above the mean might all come from the same few categories. In our result, we drafted DeAndre Jordan, Blake Griffin, Andre Drummond, and Marc Gasol, meaning we’ve probably overkilled blocks and rebounds. Our money may have been better spent in other categories.</p><p><strong>We used a single data source for values</strong> — sampling from a pool of different projections might bring us slightly closer to a player’s true performance for the season. We did not take a player’s performance variance into account at all, instead assuming that their projected stats happen with 100% certainty.</p><p><strong>Outliers distort our variance</strong> — even a few outliers can inflate variance for that category, pushing down the scores of other players for that category. A robust measure of variability that accounts for outliers is <a href="http://en.wikipedia.org/wiki/Median_absolute_deviation">Median Absolute Deviation</a>. Some method using MAD may work better, but the modified z-score using MAD inflates outlier scores even more in my analysis.</p><p><strong>We don’t account for data dependence</strong> — the stat categories are not independently distributed data. A player with a high 3pm will also tend to have more points; a player with more rebounds likely has fewer assists. We don’t account for this, but it may not affect our analysis since we wanted to capture excellence in as many categories as possible without preference for category.</p><p>Comments on improvements are more than welcome!</p><h4>Appendix — The basic rules of fantasy basketball</h4><p>A league usually consists of 12–16 team managers, each of whom have 13 NBA players on their fantasy team. Each player has 9 associated stat categories by which matches are scored: field goal percentage (FG%), free throw percentage (FT%), 3-pointers made (3pm), rebounds (reb), assists (ast), steals (stl), blocks (blk), points (pts), and turnovers (to). If Kobe Bryant is on my fantasy team, then when he grabs a rebound, my team’s reb score goes up by 1; when makes a steal, my stl score will go up by 1; when he makes a 3-pointer, my team’s 3pm score will go up by 1, my team’s pts score will go up by 3, and my team’s FG% will increase. The higher the number the better, except in the case of turnovers, where lower is better. Each week, every team in the league faces off against another team that week. The team and the end of the week who has a higher score in a majority of the stat categories wins.</p><p>Managers can bid for players throughout the entire season, but each manager must select 13 players to begin with. The draft is the process at the beginning of the fantasy season that allows managers to select their starting roster.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c94967464908" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fun-with-data-and-stats/drafting-a-fantasy-basketball-team-c94967464908">Drafting a Fantasy Basketball Team With Help From Statistics and a Knapsack</a> was originally published in <a href="https://medium.com/fun-with-data-and-stats">Fun with data and stats</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mapping Yelp Reviews Across San Francisco]]></title>
            <link>https://medium.com/fun-with-data-and-stats/mapping-yelp-ratings-across-san-francisco-c0460e864f21?source=rss----b07a190ff69d---4</link>
            <guid isPermaLink="false">https://medium.com/p/c0460e864f21</guid>
            <category><![CDATA[food]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[san-francisco]]></category>
            <dc:creator><![CDATA[Steven Tang]]></dc:creator>
            <pubDate>Sun, 06 Sep 2015 00:13:24 GMT</pubDate>
            <atom:updated>2015-08-05T21:17:30.765Z</atom:updated>
            <content:encoded><![CDATA[<p>A significant portion of my life is dedicated to finding and eating at the best-reviewed (according to Yelp) restaurants in San Francisco. Some questions naturally arise — are there certain neighborhoods that contain higher rated restaurants? Are highly rated restaurants clustered together or spread out evenly throughout the city? The Yelp API can give us the data to answer these questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7vdZFDmi889NEanIrbi5w.png" /></figure><p>A few things to know about this map and the data that’s represented:</p><ul><li>Each box is colored to reflect the average ratings of the top 10 Yelp search results for “restaurant” within that geographical boundary.</li><li>A box on the map is only colored if there were at least 2 restaurants with at least 10 reviews within that boundary.</li><li>The Yelp API only responds with ratings in increments of 0.5, so the true average rating might not be totally accurate, but I think it’s good enough for our purposes.</li></ul><h3>The Best and the Worst</h3><p>Let’s take a look at the best and worst of SF’s Yelp ratings.</p><p>Here’s a map of areas that have average ratings greater than 4.0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PV6-Shk_50ZC3wVJr9l0Rw.png" /></figure><p>…and on the flip side, areas where the average rating is under 3.5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-8NXfrs0CNPnRxI9rWMGqA.png" /></figure><p>From an unscientific glance at the map, it seems that there are a high concentration of highly reviewed restaurants in North Beach, Downtown, and the Mission. The worst-reviewed restaurants are spread more evenly throughout the city, though there don’t appear to be any particularly bad places in the areas where the top ones are.</p><p>Let’s take a closer look at the top two geographical boxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*yWkX27isKNqBJ6pAQMx3Xw.png" /></figure><p><strong>Northern tip of Ocean Beach (4.5 average rating)</strong></p><p><a href="http://www.yelp.com/biz/kawikas-ocean-beach-deli-san-francisco">Kawika’s Ocean Beach Deli</a> (4.5)</p><p><a href="http://www.yelp.com/biz/tj-cafe-san-francisco">TJ’s Cafe</a> (4.5)</p><p>A small sample size gives this area a boost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*34jMZA7hAPlBNd9yKVFvSg.png" /></figure><p><strong>North Beach / Fort Mason (4.35 average rating)</strong></p><p><a href="http://www.yelp.com/biz/the-codmother-fish-and-chips-san-francisco">Codmother Fish and Chips</a> (4.5)</p><p><a href="http://www.yelp.com/biz/hollywood-cafe-san-francisco">Hollywood Cafe</a> (4.5)</p><p><a href="http://www.yelp.com/biz/tanguito-san-francisco">Tanguito</a> (4.5)</p><p><a href="http://www.yelp.com/biz/hot-spud-san-francisco">Hot Spud</a> (4.5)</p><p><a href="http://www.yelp.com/biz/fior-d-italia-san-francisco-4">Fior d’Italia</a> (4.0)</p><p>along with <a href="http://www.yelp.com/biz/carmel-pizza-company-san-francisco">Carmel Pizza Company</a> (4.5), <a href="http://www.yelp.com/biz/3-potato-4-san-francisco-2">3 Potato 4</a> (4.5), <a href="http://www.yelp.com/biz/albona-ristorante-istriano-san-francisco">Albona Ristorante Istrano</a> (4.5), <a href="http://www.yelp.com/biz/darrens-cafe-san-francisco">Darren’s Cafe</a> (4.0), <a href="http://www.yelp.com/biz/in-n-out-burger-san-francisco">In-N-Out Burger</a> (4.0). If I had to pinpoint one small area with a high concentration of highly reviewed restaurants, it’d be this one.</p><p>And the losers of this entire analysis are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*7HE9exTa09Pi8vlqG_wazA.png" /></figure><p><strong>Daly City / Ingleside Heights border (2.33)</strong></p><p><a href="http://www.yelp.com/biz/chef-ming-san-francisco">Chef Ming</a> (2.5)</p><p><a href="http://www.yelp.com/biz/golden-wok-san-francisco">Golden Wok</a> (2.0)</p><p><a href="http://www.yelp.com/biz/china-hut-san-francisco">China Hut</a> (2.5)</p><p>This is a hub for truly terrible Chinese food.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*TEl7QYKnRxBagkew6ELlEQ.png" /></figure><p><strong>Noriega Street, Outer Sunset (2.75)</strong></p><p><a href="http://www.yelp.com/biz/eggettes-san-francisco">Eggettes</a> (3.5)</p><p><a href="http://www.yelp.com/biz/dominos-pizza-san-francisco">Domino’s Pizza</a> (2.0)</p><p>There’s just not much here.</p><p>Keep in mind that this doesn’t tell us where the best restaurants are, merely where to find ones that have been rated the highest by Yelp reviewers. Correlation between rating and “goodness” is a question for another time.</p><p>Furthermore, a high Yelp rating in one area is not equivalent to a high Yelp rating in another. Maybe people who eat/review in North Beach are particularly optimistic about their food while the Chinese take-out patrons in Ingelside are particularly prone to complaining on the Internet. I’ve also noticed that Asian restaurants in SF tend to have lower ratings than non-Asian places (Service is generally worse? Asian eaters are grumpier?). Even in an area as small as SF, it’s difficult to say that any two Yelp ratings can be considered equally. But if you have faith in the power of the Yelp reviewers, I hope I’ve been able to help you narrow your search for the next great (or terrible) thing.</p><p>I <a href="https://github.com/steventang/yelp-sf-ratings">used</a> the beautiful maps generated at <a href="http://maps.stamen.com/#toner/12/37.7706/-122.3782">stamen</a> to visualize San Francisco, the Yelp API for data, and D3 for visualization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0460e864f21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fun-with-data-and-stats/mapping-yelp-ratings-across-san-francisco-c0460e864f21">Mapping Yelp Reviews Across San Francisco</a> was originally published in <a href="https://medium.com/fun-with-data-and-stats">Fun with data and stats</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing Artist Collaborations in the Billboard Top 10 Songs]]></title>
            <link>https://medium.com/fun-with-data-and-stats/visualizing-artist-collaborations-in-the-billboard-top-10-songs-ff6188a0f57b?source=rss----b07a190ff69d---4</link>
            <guid isPermaLink="false">https://medium.com/p/ff6188a0f57b</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Steven Tang]]></dc:creator>
            <pubDate>Sun, 06 Sep 2015 00:12:40 GMT</pubDate>
            <atom:updated>2015-09-05T20:34:28.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78TATrW3nxTWKDoDd-asNw.png" /></figure><p><strong><em>Preface:</em></strong><em> I highly recommend taking a look at the </em><a href="http://steventang.github.io/billboard-top-collaborations/"><em>HTML renderings</em></a><em> of the charts contained in this post. You can also see all the charts in one place if you don’t want to read. For the force-directed graph especially, you can examine the relationships in the data more closely. You can see them here: </em><a href="http://steventang.github.io/billboard-top-collaborations/">http://steventang.github.io/billboard-top-collaborations/</a></p><p>I took a glance at the <a href="http://www.billboard.com/charts/hot-100">Billboard Top 10</a> charts recently and was surprised to find so many songs where artists had collaborated, i.e. where an artist features one or more other artists (e.g. <em>Lean On</em> by Major Lazer &amp; DJ Snake Featuring M0). I became curious as to whether artists have started collaborating more in recent years so I set out to find the answer. Along the way, I took a look at a few other aspects of the dataset for fun and drew some charts for your viewing pleasure.</p><p>Let’s kick it off with a simple one before getting into any analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*CzfbEUNzQ5C_IGGY7CyHgQ.png" /></figure><p>This one is pretty straightforward, the proportion of spots in the Top 10 every year that are taken by collaborations.</p><h4>The Dataset</h4><p>Billboard’s datasets aren’t publicly available. Billboard offers “Research Services” for $200/hr if you need to get neatly presented data delivered to you. That seemed a bit steep. Luckily, I discovered that Billboard keeps a complete history of weekly Hot 100 charts at a distinct, easily guessable URL (for example, check out <a href="http://www.billboard.com/charts/hot-100/1990-01-06">http://www.billboard.com/charts/hot-100/1990-01-06</a>). I wrote a simple web parser to scrape the data from Billboard’s site, holding true to my philosophy that data collection should always be performed frugally.</p><p>For this analysis, I decided to use only the Top 10 songs every week, starting from January 6, 1990 and ending on August 22, 2015. I only wanted to examine collaborations in the most popular songs. With this in mind, I won’t make any sweeping generalizations about collaborations as a whole, limiting our scope to the most popular collaborations.</p><p>It wasn’t trivial to determine whether or not a song should count as collaboration; checking over 13,000 songs requires a bit of work. I decided to split each whole artist string by key symbols such as “&amp;”, “,”, and “Featuring”, then did a few edits for when this heuristic failed. I’m fairly confident that I accurately determined whether a song is collaborative for the vast majority of cases, but I would be surprised if nothing slipped through at all. Feel free to check the work <a href="https://github.com/steventang/billboard-top-collaborations">here</a>.</p><h4>An Upward Trend</h4><p>Back to the chart above — the percent of collaborative songs per year has shown an upward trend since 1990. The boom in collaborations starts in 2001 and reaches its peak at 2003 before leveling off for the next decade. So no, artists haven’t been collaborating more than they have been in the recent past. Collaborations have been in vogue for the last 10 years. In fact, 2015 so far has seen a sharp dip in the proportion of collaborations in the Top 10.</p><p>Things aren’t too different for Billboard’s weekly #1 songs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*CheuvpHQUHmvV-HGd3DWnw.png" /></figure><p>A scatterplot of the number of collaborative songs every week reveals a few interesting tidbits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*zHea1UfO7_M7YmjH3mBe6Q.png" /></figure><p>Most notably, there’s an entire decade, from 2002–2012, in which not a single week went by without a collaborative song in the Top 10.</p><p><strong>Fact:</strong></p><blockquote>Throughout the period of Jan 1990 — Aug 2015, 23.59% of all unique songs in the Top 10 were collaborations.</blockquote><p>That isn’t to say 23.59% of all spots in the weekly Top 10 are taken by collaborative songs, but rather that amongst all of the distinct songs to reach the Top 10 in that period, 23.59% were collaborative.</p><p><strong>Here’s a more difficult question to answer:</strong> why did collaborations increase in the early 2000&#39;s? We can’t say that it’s because artists realized collaborations are valuable, or because listener’s shifted their tastes. Perhaps the artists who rose to popularity in the 2000&#39;s come from genres that tend to favor collaborations. Much more data is required to explain confounding variables here, but my best guess is that the rise of Hip Hop contributed greatly to the rise in collaborations. Hip Hop is a genre that makes heavy use of collaborations and it rose into the pop music mainstream in the late 1990&#39;s and early 2000&#39;s.</p><p>The next chart somewhat affirms this belief:</p><h4>The Most Collaborative Artists</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*7QyU5OjS2SUEKpiAMFtWKQ.png" /></figure><p>The chart above shows the artists who’ve spent the most weeks in the Top 10 with collaborative songs. I’ve also delineated how many weeks each artist had a song in which they’re credited as the lead artist. Boss Lady J.Lo ain’t getting featured on nobody’s tunes.</p><p>Similarly, we can examine how many <em>unique songs</em> each artist has placed in the Top 10:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*AkCFvr-QKPp2IMs4TeIXoQ.png" /></figure><p>The top collaborators are largely Hip Hop and R&amp;B artists. Did the success of these artists give rise to the popularity of collaborations or did they just follow the secular rise in multi-artist hits? Unfortunately I don’t think I have enough data to answer this right now.</p><h4>How artists are connected</h4><p>I’ll define an artist as “connected” to another if they’ve collaborated on a song together. The graph below shows how artists who have been a part of the most distinct collaborative songs in the Top 10 are connected. The first graph shows the connections between the 100 top artists (For a more fun version of this graph, click <a href="http://steventang.github.io/billboard-top-collaborations/">here</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78TATrW3nxTWKDoDd-asNw.png" /></figure><p>The width of the lines represents how many distinct songs each pair of artists has collaborated on. Lil’ Wayne and Drake, with 5 songs in the Top 10, are the two most connected artists.</p><p>Admittedly, the graph above contains perhaps an excess of information. Let’s shrink it down to the top 20 artists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*IfPaf2yy9MhPO5ZIyOVVPw.png" /></figure><p><em>You can find the interactive HTML versions of these graphs </em><a href="http://steventang.github.io/billboard-top-collaborations/"><em>here</em></a><em>.</em></p><p><em>You can find the data </em><a href="https://github.com/steventang/billboard-top-collaborations/tree/master/data"><em>here</em></a><em>.</em> <em>If you have any ideas about what interesting insights could be pulled from this dataset, let me know or use it yourself!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff6188a0f57b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fun-with-data-and-stats/visualizing-artist-collaborations-in-the-billboard-top-10-songs-ff6188a0f57b">Visualizing Artist Collaborations in the Billboard Top 10 Songs</a> was originally published in <a href="https://medium.com/fun-with-data-and-stats">Fun with data and stats</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>