Data Scraping Instagram for Likes

Posted on Nov 21, 2016
The skills the author demoed here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.

Introduction:

In the exponentially growing digital age, the internet is flooded with data. Along with the advent of smartphones equipped with high-definition cameras,Β personal pictures have become an integral part of social media. In particular, some social media mobile applicationsΒ chooses photo-sharing as their main platform.Β One of the most popular photo-sharing applications is Instagram, where millions of users share curated photosΒ in hopes of becoming "insta-famous" with a large number of followers, likes, and comments.

"A picture is worth a thousand words"

The above phrase is a very common and widely used to imply that pictures often contains a surplus of information. Until now, this quote was mainly geared toward humans interpretingΒ information from pictures individually. Although in principle, one can make strong conclusions from plethora of data in images, it is not efficient or desired to go through each and every image by hand. Fortunately,Β with the growth in the computer vision technology and powerful computing resources, we are inching closer to automating low-error extraction of information from images. This information can potentially give us a whole new dimension of data toΒ use.

In this project, the ultimate goal was to use image classification technology to process Instagram photos to gain insights about @instagram account. In this blog, I will detail how to scrape Instagram photos without using the API explicitly, instead using Python's Scrapy package. Next, I will describe the different image classification technologies, Google's Inception and Clarifai, and examples of good and bad classifications. Finally, some exploratory analysis was done to find the top-liked and commentedΒ classifications. This blog will end with some next steps to improve upon this workflow and correct lessons learned throughout this project.

Data:

The data for this project was scraped from the @Instagram account. At the point in time when it was scraped, 3346 images were downloaded. The reason this account was used as the first prototype was because it has a heavy following (over 199 million followers) and a diverse set of photos pulled from the Instagram community. It was assumed that would be aΒ close representation of the diverse populationΒ of Instagram users.

Data Web Scraping:

Data Scraping Instagram for Likes

Instagram webpage

Scraping Instagram proved to be difficult because the developersΒ made their data not easily accessible. Although they have an API, it was geared towards businessesΒ looking to advertise their brands. Furthermore, their website was dynamically loaded with AJAX calls, making it a prime candidate forΒ a package like Selenium that uses aΒ bot that manually records information. Luckily, a proxy site called imgrum.net has done half of the heavy-lifting by building a simplified web display of Instagram photos by pulling data from their API. With that repository in place, instead of Selenium, Scrapy was used as the scraping package for this project.

Data Scraping Instagram for Likes

Imgrum Webpage

Here is the Imgrum website that lays out the images, numbers of likes, and numbers of comments in plain sight. A quick inspection of the HTMLΒ source code, we can find that each image and its associated likes and comments are stored in separate classes. Going one level deeper, we can extract the image url, number of likes, and number of comments.

Now that we discerned a pattern in the source code, Scrapy was used to deploy a Scrapy spider to crawl through the website recording all this information into a .csv file. Lastly,Β each set of images are stored on pages on the website, so after the spider extracted all the image information, the "Next" page link was extracted to load the next webpage. The scraping concludes when there are no more pages to crawl.

Image Classifiers:

Convolutional Neural Networks

AsΒ I mentionedΒ earlier, two different classifiers were used on the images. The first being Google's Inception model, and second beingΒ Clarifai's computer vision API.Β The underlyingΒ algorithmΒ that both models rely onΒ are convolutional neural networks(CNN). A CNN isΒ a deep learning algorithm that recently became popular in the computer vision community back in 2012 when it was used to win that year's ImageNet competition.

Before then, computer vision algorithm used a whole collection of feature detectionΒ algorithms to first extract features from the image,Β before putting it through a standard classifier like logistic regression or support vector machines. Despite the hard work in extracting features in a preprocessing step, the accuracy of these algorithms were still subpar. The lowest error rateΒ was about 23% in 2011's ImageNet competition.Β When CNN's were first used in 2012 by AlexNet, it won the ImageNet competition that year with about 16% error rate, 7% better than the previous year. Currently, the best image classification model evenΒ surpasses average human performance.

ImageNet

Data Scraping Instagram for Likes

https://devblogs.nvidia.com/parallelforall/ | Error rate

CNN's on the other hand, does the feature extraction for you automatically. This is done by adding convolutional layers as the first couple of hidden layers in a Neural Network. The convolutional layers use a sliding window operation that runs across the image pixels and performs a filtering operationΒ to create a set of new abstract features. Each convolutional layer will further create even more abstract features for the neural network to use.

For example, in facial recognition, the first convolutional layer will transform the data from a set of pixel values to a set of detected edges. The second layer will transform the set of edges to a set of simple shapes. The third layer may recognize facial features such as a nose or mouth. The process will continue until you have a set of faces that can be used as a basis to recognize a given face. A typical CNN architecture will look like:

convnet

http://www.wildml.com/2015/11/understanding-convolutional-neural-networks-for-nlp/

Google Inception Model

The first of the two classifiers used was Google's Inception image classifier. Β Their model was the winner in the 2014 ImageNet competition that had the lowest error rate of 6.7% when it came to classifying images into 1000 different classes. The model was trained on an enormous data set of over one million images.Β This model was released to the public in 2015 along with their code using their deep learning framework, TensorFlow, to classify new images.

screen-shot-2016-12-01-at-2-38-18-pm

Here is an example of using this technology to classify a picture of a lion. The top-five classes and their probabilities are given as output. What is not shown is the 995 other classes that usually have very low probability scores. In this case, the classifier is over 90% sure that this is a photo of a lion. So far it is performing fairly well.

screen-shot-2016-12-01-at-2-39-34-pm

Here is an example of trying to run this classification on a collage of images. The model now performs poorly forΒ multiple reasons. First, the model wants to classify multiple things at once, but it can only have a total probability of 1, so it starts to split the confidence among multiple classes. Second, the image is not homogenous, so this confuses the image classifier. Lastly, some of the things in the images may not belong to any of the 1000 classes, so the classifier will try its best to guess the closest class it knows.

Clarifai's API

The second of the two classifiers is Clarifai's software. Clarifai is a computer vision AI startup that hopes to bring complex and intensive computer vision services to businesses in the form of easy to use APIs. Clarifai is also built using convolutional neural networks, but it also has a region selection algorithm as well. This allows the multiple objects and classes to be extracted from the image. Specific detail of Clarifai's algorithm is unknown since it is proprietary technology.

screen-shot-2016-12-01-at-2-40-08-pm

Here is an example of Clarifai classifying an abstract image of a man flying through the sky with balloons. Although this image is more artistic than realistic, with Clarifai's regional detection algorithm, it was able to accurately predict what was inside the image. It also has classes that seemed to be more general than Google's classifier.

screen-shot-2016-12-01-at-2-40-25-pm

Here is an example of Clarifai classifying a man holding an obsolete camera. It was able to correctly classify the man and his hat, but mistakenly classified the camera as a gun/weapon.

Exploratory Data Analysis:

class_commentsclass_likes

After processing each image, and classifying the images with these two models, some preliminary exploratory analysis was performed. A weighted average was used here to penalized classes that had low probabilities. Here are the top 10 classes for both number of likes and number of comments using Google's Inception classifier. It turns out that the top 10 classifications are mostly pictures of outliers. Looking deeper into the data set, surprisingly, most of these classes were only reported with high probability on one image.

object_commentsobject_likes

Likewise, although Clarifai had classes that were more general, some of these classes were also only reported with high probability on one image.

Conclusion:

  • Web scraping is messy and sometimes nearly out your control (server problems)

  • Computer vision is pretty awesome (but needs work)

  • Not all data will be nicely distributed, outliers dominated the top liked and comments photos

  • Clarifai’s system seem to be better than the Google classifier, but would cost money

Next Steps:

  • Scrape comments and do Natural Language Processing to gain more insight

  • Use other computer vision models, i.e Google’s Show and Tell or Caffe Model Zoo

  • Train new model for specific category (i.e food) and perform similar analysis but on food Instagram

  • Fit machine learning model to predict the number of likes/comments

If you are interested in seeing the nitty-gritty details of the code, please visit my GitHub!

About Author

Nelson Chen

Nelson has a Bachelor's degree from Northwestern University and a Master's degree from University of California, Berkeley in Mechanical Engineering. His graduate work specialized in developing and applying new Computational Fluid Dynamic algorithms to astrophysical fluid dynamic problems...
View all posts by Nelson Chen >

Related Articles

Leave a Comment

No comments found.

View Posts by Categories


Our Recent Popular Posts


View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI