<jupyter_start><jupyter_text>A Python Tour of Data Science: Data Acquisition & Exploration     [<NAME>](http://deff.ch), *PhD student*, [EPFL](http://epfl.ch) [LTS2](http://lts2.epfl.ch)  Exercise: problem definitionTheme 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](https://www.google.com/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 importation1. 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](01_sol_acquisition_exploration.ipynb).<jupyter_code>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.<jupyter_output><empty_output><jupyter_text>2 VectorizationFirst 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*](https://en.wikipedia.org/wiki/Bag-of-words_model) 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](http://www.nltk.org/) and [gensim](https://radimrehurek.com/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 ?<jupyter_code>from sklearn.feature_extraction.text import CountVectorizer

nwords = 100

# Your code here.<jupyter_output><empty_output><jupyter_text>Exploration question: what are the 5 most used words ? Exploring your data while playing with it is a useful sanity check.<jupyter_code># Your code here.<jupyter_output><empty_output><jupyter_text>3 Pre-processing1. 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.<jupyter_code># Your code here.<jupyter_output><empty_output><jupyter_text>4 Linear regressionUsing `numpy`, fit and evaluate the [linear model](https://en.wikipedia.org/wiki/Linear_regression) $$\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()`.<jupyter_code>import scipy.sparse

# Your code here.<jupyter_output><empty_output><jupyter_text>Interpretation: what are the most important words a post / tweet should include ?<jupyter_code># Your code here.<jupyter_output><empty_output><jupyter_text>5 Interactivity1. 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.<jupyter_code>import ipywidgets
from IPython.display import clear_output

# Your code here.<jupyter_output><empty_output><jupyter_text>6 Scikit learn1. 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.<jupyter_code>from sklearn import linear_model, metrics

# Your code here.<jupyter_output><empty_output><jupyter_text>7 Deep LearningTry 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.<jupyter_code>import os
os.environ['KERAS_BACKEND'] = 'theano'  # tensorflow
import keras

# Your code here.<jupyter_output><empty_output><jupyter_text>8 EvaluationUse [matplotlib](http://matplotlib.org) 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 ?<jupyter_code>from matplotlib import pyplot as plt
plt.style.use('ggplot')
%matplotlib inline

# Your code here.<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0944214097248398, 'fraction_numerical': 0.010554089709762533, 'mean_word_length': 4.7747551686615886, 'pattern_counts': {'":': 0, '<': 42, '<?xml version=': 0, '>': 43, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '357421', 'license': 'MIT', 'n_tokens_mistral': 1583, 'n_tokens_neox': 1524, 'n_words': 636, 'path': 'toolkit/02_ex_exploitation.ipynb', 'repo_name': 'vinceHardy/learning', 'size': '5318'}