A Python Tour of Data Science: Data Acquisition & Exploration

Michaël Defferrard, PhD student, EPFL LTS2

Exercise: problem definition

Theme of the exercise: understand the impact of your communication on social networks. A real life situation: the marketing team needs help in identifying which were the most engaging posts they made on social platforms to prepare their next AdWords campaign.

This notebook is the second part of the exercise. Given the data we collected from Facebook an Twitter in the last exercise, we will construct an ML model and evaluate how good it is to predict the number of likes of a post / tweet given the content.

1 Data importation

  1. Use pandas to import the facebook.sqlite and twitter.sqlite databases.
  2. Print the 5 first rows of both tables.

The facebook.sqlite and twitter.sqlite SQLite databases can be created by running the data acquisition and exploration exercise.


In [ ]:
import pandas as pd
import numpy as np
from IPython.display import display
import os.path

folder = os.path.join('..', 'data', 'social_media')

# Your code here.

2 Vectorization

First step: transform the data into a format understandable by the machine. What to do with text ? A common choice is the so-called bag-of-word model, where we represent each word a an integer and simply count the number of appearances of a word into a document.

Example

Let's say we have a vocabulary represented by the following correspondance table.

Integer Word
0 unknown
1 dog
2 school
3 cat
4 house
5 work
6 animal

Then we can represent the following document

I have a cat. Cats are my preferred animals.

by the vector $x = [6, 0, 0, 2, 0, 0, 1]^T$.

Tasks

  1. Construct a vocabulary of the 100 most occuring words in your dataset.
  2. Build a vector $x \in \mathbb{R}^{100}$ for each document (post or tweet).

Tip: the natural language modeling libraries nltk and gensim are useful for advanced operations. You don't need them here.

Arise a first data cleaning question. We may have some text in french and other in english. What do we do ?


In [ ]:
from sklearn.feature_extraction.text import CountVectorizer

nwords = 100

# Your code here.

Exploration question: what are the 5 most used words ? Exploring your data while playing with it is a useful sanity check.


In [ ]:
# Your code here.

3 Pre-processing

  1. The independant variables $X$ are the bags of words.
  2. The target $y$ is the number of likes.
  3. Split in half for training and testing sets.

In [ ]:
# Your code here.

4 Linear regression

Using numpy, fit and evaluate the linear model $$\hat{w}, \hat{b} = \operatorname*{arg min}_{w,b} \| Xw + b - y \|_2^2.$$

Please define a class LinearRegression with two methods:

  1. fit learn the parameters $w$ and $b$ of the model given the training examples.
  2. predict gives the estimated number of likes of a post / tweet. That will be used to evaluate the model on the testing set.

To evaluate the classifier, create an accuracy(y_pred, y_true) function which computes the mean squared error $\frac1n \| \hat{y} - y \|_2^2$.

Hint: you may want to use the function scipy.sparse.linalg.spsolve().


In [ ]:
import scipy.sparse

# Your code here.

Interpretation: what are the most important words a post / tweet should include ?


In [ ]:
# Your code here.

5 Interactivity

  1. Create a slider for the number of words, i.e. the dimensionality of the samples $x$.
  2. Print the accuracy for each change on the slider.

In [ ]:
import ipywidgets
from IPython.display import clear_output

# Your code here.

6 Scikit learn

  1. Fit and evaluate the linear regression model using sklearn.
  2. Evaluate the model with the mean squared error metric provided by sklearn.
  3. Compare with your implementation.

In [ ]:
from sklearn import linear_model, metrics

# Your code here.

7 Deep Learning

Try a simple deep learning model !

Another modeling choice would be to use a Recurrent Neural Network (RNN) and feed it the sentence words after words.


In [ ]:
import os
os.environ['KERAS_BACKEND'] = 'theano'  # tensorflow
import keras

# Your code here.

8 Evaluation

Use matplotlib to plot a performance visualization. E.g. the true number of likes and the real number of likes for all posts / tweets.

What do you observe ? What are your suggestions to improve the performance ?


In [ ]:
from matplotlib import pyplot as plt
plt.style.use('ggplot')
%matplotlib inline

# Your code here.