#!/usr/bin/env python
# coding: utf-8
# # text mining (nlp) with python
# **Author:** Ties de Kok ([Personal Website](https://www.tiesdekok.com))
# **Last updated:** June 2020
# **Python version:** Python 3.7
# **License:** MIT License
# **Note:** Some features (like the ToC) will only work if you run the notebook or if you use nbviewer by clicking this link:
# https://nbviewer.jupyter.org/github/TiesdeKok/Python_NLP_Tutorial/blob/master/NLP_Notebook.ipynb
# # *Introduction*
# This notebook contains code examples to get you started with Python for Natural Language Processing (NLP) / Text Mining.
#
# In the large scheme of things there are roughly 4 steps:
#
# 1. Identify a data source
# 2. Gather the data
# 3. Process the data
# 4. Analyze the data
#
# This notebook only discusses step 3 and 4. If you want to learn more about step 2 see my [Python tutorial](https://github.com/TiesdeKok/LearnPythonforResearch).
# ## Note: companion slides
# This notebook was designed to accompany a PhD course session on NLP techniques in Accounting Research.
# The slides of this session are publically availabe here: [Slides](http://www.tiesdekok.com/AccountingNLP_Slides/)
# # *Elements / topics that are discussed in this notebook:*
#
#
#
# # *Table of Contents*
# * [Primer on NLP tools](#tool_primer)
# * [Process + Clean text](#proc_clean)
# * [Normalization](#normalization)
# * [Deal with unwanted characters](#unwanted_char)
# * [Sentence segmentation](#sentence_seg)
# * [Word tokenization](#word_token)
# * [Lemmatization & Stemming](#lem_and_stem)
# * [Language modeling](#lang_model)
# * [Part-of-Speech tagging](#pos_tagging)
# * [Uni-Gram & N-Grams](#n_grams)
# * [Stop words](#stop_words)
# * [Direct feature extraction](#feature_extract)
# * [Feature search](#feature_search)
# * [Entity recognition](#entity_recognition)
# * [Pattern search](#pattern_search)
# * [Text evaluation](#text_eval)
# * [Language](#language)
# * [Dictionary counting](#dict_counting)
# * [Readability](#readability)
# * [Represent text numerically](#text_numerical)
# * [Bag of Words](#bows)
# * [TF-IDF](#tfidf)
# * [Word Embeddings](#word_embed)
# * [Spacy](#spacyEmbedding)
# * [Word2Vec](#Word2Vec)
# * [Statistical models](#stat_models)
# * ["Traditional" machine learning](#trad_ml)
# * [Supervised](#trad_ml_supervised)
# * [Naïve Bayes](#trad_ml_supervised_nb)
# * [Support Vector Machines (SVM)](#trad_ml_supervised_svm)
# * [Unsupervised](#trad_ml_unsupervised)
# * [Latent Dirichilet Allocation (LDA)](#trad_ml_unsupervised_lda)
# * [pyLDAvis](#trad_ml_unsupervised_pyLDAvis)
# * [Model Selection and Evaluation](#trad_ml_eval)
# * [Neural Networks](#nn_ml)
# # Primer on NLP tools [(to top)](#toc)
# There are many tools available for NLP purposes.
# The code examples below are based on what I personally like to use, it is not intended to be a comprehsnive overview.
#
# Besides build-in Python functionality I will use / demonstrate the following packages:
#
# **Standard NLP libraries**:
# 1. `Spacy`
# 2. `NLTK` and the higher-level wrapper `TextBlob`
#
# *Note: besides installing the above packages you also often have to download (model) data . Make sure to check the documentation!*
#
# **Standard machine learning library**:
#
# 1. `scikit learn`
#
# **Specific task libraries**:
#
# There are many, just a couple of examples:
#
# 1. `pyLDAvis` for visualizing LDA)
# 2. `langdetect` for detecting languages
# 3. `fuzzywuzzy` for fuzzy text matching
# 4. `Gensim` for topic modelling
# # Get some example data [(to top)](#toc)
# There are many example datasets available to play around with, see for example this great repository:
# https://archive.ics.uci.edu/ml/datasets.php
# The data that I will use for most of the examples is the "Reuter_50_50 Data Set" that is used for author identification experiments.
#
# See the details here: https://archive.ics.uci.edu/ml/datasets/Reuter_50_50
# ### Download and load the data
# Can't follow what I am doing here? Please see my [Python tutorial](https://github.com/TiesdeKok/LearnPythonforResearch) (although the `zipfile` and `io` operations are not very relevant).
# In[1]:
import requests, zipfile, io, os
from tqdm.notebook import tqdm
# *Note:* for `tqdm` to work in JupyterLab you need to install the `@jupyter-widgets/jupyterlab-manager` using the puzzle icon in the left side bar.
# *Download and extract the zip file with the data *
# In[2]:
if not os.path.exists('C50test'):
r = requests.get("https://archive.ics.uci.edu/ml/machine-learning-databases/00217/C50.zip")
z = zipfile.ZipFile(io.BytesIO(r.content))
z.extractall()
# *Load the data into memory*
# In[3]:
folder_dict = {'test' : 'C50test'}
text_dict = {'test' : {}}
# In[4]:
for label, folder in tqdm(folder_dict.items()):
authors = os.listdir(folder)
for author in authors:
text_files = os.listdir(os.path.join(folder, author))
for file in text_files:
with open(os.path.join(folder, author, file), 'r') as text_file:
text_dict[label].setdefault(author, []).append(' '.join(text_file.readlines()))
# *Note: the text comes pre-split per sentence, for the sake of example I undo this through `' '.join(text_file.readlines()`*
# In[5]:
text_dict['test']['TimFarrand'][0]
# # Process + Clean text [(to top)](#toc)
# ## Convert the text into a NLP representation
# We can use the text directly, but if want to use packages like `spacy` and `textblob` we first have to convert the text into a corresponding object.
# ### Spacy
# **Note:** depending on the way that you installed the language models you will need to import it differently:
# ```
# from spacy.en import English
# nlp = English()
# ```
# OR
# ```
# import en_core_web_sm
# nlp = en_core_web_sm.load()
#
# import en_core_web_md
# nlp = en_core_web_md.load()
#
# import en_core_web_lg
# nlp = en_core_web_lg.load()
# ```
# In[6]:
import spacy
import en_core_web_md
nlp = en_core_web_md.load()
# Convert all text in the "test" sample to a `spacy` `doc` object using `nlp.pipe()`:
# In[7]:
spacy_text = {}
for author, text_list in tqdm(text_dict['test'].items()):
spacy_text[author] = list(nlp.pipe(text_list))
# *A note on speed:* This is slow because we didn't disable any compontents, see this note from the documentation:
# > Only apply the pipeline components you need. Getting predictions from the model that you don’t actually need adds up and becomes very inefficient at scale. To prevent this, use the disable keyword argument to disable components you don’t need – either when loading a model, or during processing with nlp.pipe. See the section on disabling pipeline components for more details and examples. [link](https://spacy.io/usage/processing-pipelines#disabling)
# In[8]:
type(spacy_text['TimFarrand'][0])
# ### NLTK
# In[9]:
import nltk
# We can apply basic `nltk` operations directly to the text so we don't need to convert first.
# ### TextBlob
# In[10]:
from textblob import TextBlob
# Convert all text in the "test" sample to a `TextBlob` object using `TextBlob()`:
# In[11]:
textblob_text = {}
for author, text_list in text_dict['test'].items():
textblob_text[author] = [TextBlob(text) for text in text_list]
# In[12]:
type(textblob_text['TimFarrand'][0])
# ## Normalization [(to top)](#toc)
# **Text normalization** describes the task of transforming the text into a different (more comparable) form.
#
# This can imply many things, I will show a couple of options below:
# ### Deal with unwanted characters [(to top)](#toc)
# You will often notice that there are characters that you don't want in your text.
#
# Let's look at this sentence for example:
#
# > "Shares in brewing-to-leisure group Bass Plc are likely to be held back until Britain\'s Trade and Industry secretary Ian Lang decides whether to allow its proposed merge with brewer Carlsberg-Tetley, said analysts.\n Earlier Lang announced the Bass deal would be referred to the Monoplies and Mergers"
#
# You notice that there are some `\` and `\n` in there. These are used to define how a string should be displayed, if we print this text we get:
# In[13]:
text_dict['test']['TimFarrand'][0][:298]
# In[14]:
print(text_dict['test']['TimFarrand'][0][:298])
# These special characters can cause problems in our analyses (and can be hard to debug if you are using `print` statements to inspect the data).
#
# **So how do we remove them?**
# In many cases it is sufficient to simply use the `.replace()` function:
# In[15]:
text_dict['test']['TimFarrand'][0][:298].replace('\n', '').replace('\\', '')
# Sometimes, however, the problem arrises because of encoding / decoding problems.
#
# In those cases you can usually do something like:
# In[16]:
problem_sentence = 'This is some \u03c0 text that has to be cleaned\u2026! it\u0027s difficult to deal with!'
print(problem_sentence)
print(problem_sentence.encode().decode('unicode_escape').encode('ascii','ignore'))
# An alternative that is better at preserving the unicode characters would be to use `unidecode`
# In[17]:
import unidecode
# In[18]:
print('\u738b\u7389')
# In[19]:
unidecode.unidecode(u"\u738b\u7389")
# In[20]:
unidecode.unidecode(problem_sentence)
# ### Sentence segmentation [(to top)](#toc)
# Sentence segmentation refers to the task of splitting up the text by sentence.
#
# You could do this by splitting on the `.` symbol, but dots are used in many other cases as well so it is not very robust:
# In[21]:
text_dict['test']['TimFarrand'][0][:550].split('.')
# It is better to use a more sophisticated implementation such as the one by `Spacy`:
# In[22]:
example_paragraph = spacy_text['TimFarrand'][0]
# In[23]:
sentence_list = [s for s in example_paragraph.sents]
sentence_list[:5]
# Notice that the returned object is still a `spacy` object:
# In[24]:
type(sentence_list[0])
# *Note:* `spacy` sentence segmentation relies on the text being capitalized, so make sure you didn't convert it to all lower case before running this operation.
# Apply to all texts (for use later on):
# In[25]:
spacy_sentences = {}
for author, text_list in tqdm(spacy_text.items()):
spacy_sentences[author] = [list(text.sents) for text in text_list]
# In[26]:
spacy_sentences['TimFarrand'][0][:3]
# ### Word tokenization [(to top)](#toc)
# Word tokenization means to split the sentence (or text) up into words.
# In[27]:
example_sentence = spacy_sentences['TimFarrand'][0][0]
example_sentence
# A word is called a `token` in this context (hence `tokenization`), using `spacy`:
# In[28]:
token_list = [token for token in example_sentence]
token_list[0:15]
# ### Lemmatization & Stemming [(to top)](#toc)
# In some cases you want to convert a word (i.e. token) into a more general representation.
#
# For example: convert "car", "cars", "car's", "cars'" all into the word `car`.
#
# This is generally done through lemmatization / stemming (different approaches trying to achieve a similar goal).
# **Spacy**
# Space offers build-in functionality for lemmatization:
# In[29]:
lemmatized = [token.lemma_ for token in example_sentence]
lemmatized[0:15]
# **NLTK**
# Using the NLTK libary we can also use the more aggressive Porter Stemmer
# In[30]:
from nltk.stem.porter import PorterStemmer
stemmer = PorterStemmer()
# In[31]:
stemmed = [stemmer.stem(token.text) for token in example_sentence]
stemmed[0:15]
# **Compare**:
# In[32]:
print(' Original | Spacy Lemma | NLTK Stemmer')
print('-' * 41)
for original, lemma, stem in zip(token_list[:15], lemmatized[:15], stemmed[:15]):
print(str(original).rjust(10, ' '), ' | ', str(lemma).rjust(10, ' '), ' | ', str(stem).rjust(10, ' '))
# In my experience it is usually best to use lemmatization instead of a stemmer.
# ## Language modeling [(to top)](#toc)
# Text is inherently structured in complex ways, we can often use some of this underlying structure.
# ### Part-of-Speech tagging [(to top)](#toc)
# Part of speech tagging refers to the identification of words as nouns, verbs, adjectives, etc.
# Using `Spacy`:
# In[33]:
pos_list = [(token, token.pos_) for token in example_sentence]
pos_list[0:10]
# ### Uni-Gram & N-Grams [(to top)](#toc)
# Obviously a sentence is not a random collection of words, the sequence of words has information value.
#
# A simple way to incorporate some of this sequence is by using what is called `n-grams`.
# An `n-gram` is nothing more than a a combination of `N` words into one token (a uni-gram token is just one word).
#
# So we can convert `"Sentence about flying cars"` into a list of bigrams:
#
# > Sentence-about, about-flying, flying-cars
#
# See my slide on N-Grams for a more comprehensive example: [click here](http://www.tiesdekok.com/AccountingNLP_Slides/#14)
# Using `NLTK`:
# In[34]:
bigram_list = ['-'.join(x) for x in nltk.bigrams([token.text for token in example_sentence])]
bigram_list[10:15]
# Using `spacy`
# In[35]:
def tokenize_without_punctuation(sen_obj):
return [token.text for token in sen_obj if token.is_alpha]
# In[36]:
def create_ngram(sen_obj, n, sep = '-'):
token_list = tokenize_without_punctuation(sen_obj)
number_of_tokens = len(token_list)
ngram_list = []
for i, token in enumerate(token_list[:-n+1]):
ngram_item = [token_list[i + ii] for ii in range(n)]
ngram_list.append(sep.join(ngram_item))
return ngram_list
# In[37]:
create_ngram(example_sentence, 2)[:5]
# In[38]:
create_ngram(example_sentence, 3)[:5]
# ### Stop words [(to top)](#toc)
# Depending on what you are trying to do it is possible that there are many words that don't add any information value to the sentence.
#
# The primary example are stop words.
#
# Sometimes you can improve the accuracy of your model by removing stop words.
# Using `Spacy`:
# In[39]:
no_stop_words = [token for token in example_sentence if not token.is_stop]
# In[40]:
no_stop_words[:10]
# In[41]:
token_list[:10]
# *Note* we can also remove punctuation in the same way:
# In[42]:
[token for token in example_sentence if not token.is_stop and token.is_alpha][:10]
# ## Wrap everything into one function
# **Basic SpaCy text processing function**
# 1. Split into sentences
# 2. Apply lemmatizer, remove top words, remove punctuation
# 3. Clean up the sentence using `textacy`
# In[43]:
def process_text_custom(text):
sentences = list(nlp(text, disable=['tagger', 'ner', 'entity_linker', 'textcat', 'entitry_ruler']).sents)
lemmatized_sentences = []
for sentence in sentences:
lemmatized_sentences.append([token.lemma_ for token in sentence if not token.is_stop and token.is_alpha])
return [' '.join(sentence) for sentence in lemmatized_sentences]
# In[44]:
spacy_text_clean = {}
for author, text_list in tqdm(text_dict['test'].items()):
lst = []
for text in text_list:
lst.append(process_text_custom(text))
spacy_text_clean[author] = lst
# *Note:* that this would take quite a long time if we didn't disable some of the components.
# In[45]:
count = 0
for author, texts in spacy_text_clean.items():
for text in texts:
count += len(text)
print('Number of sentences:', count)
# Result
# In[46]:
spacy_text_clean['TimFarrand'][0][:3]
# *Note:* the quality of the input text is not great, so the sentence segmentation is also not great (without further tweaking).
# # Direct feature extraction [(to top)](#toc)
# We now have pre-processed our text into something that we can use for direct feature extraction or to convert it to a numerical representation.
# ## Feature search [(to top)](#toc)
# ### Entity recognition [(to top)](#toc)
# It is often useful / relevant to extract entities that are mentioned in a piece of text.
#
# SpaCy is quite powerful in extracting entities, however, it doesn't work very well on lowercase text.
#
# Given that "token.lemma\_" removes capitalization I will use `spacy_sentences` for this example.
# In[47]:
example_sentence = spacy_sentences['TimFarrand'][0][3]
example_sentence
# In[48]:
[(i, i.label_) for i in nlp(example_sentence.text).ents]
# In[49]:
example_sentence = spacy_sentences['TimFarrand'][4][0]
example_sentence
# In[50]:
[(i, i.label_) for i in nlp(example_sentence.text).ents]
# ### Pattern search [(to top)](#toc)
# Using the build-in `re` (regular expression) library you can pattern match nearly anything you want.
#
# I will not go into details about regular expressions but see here for a tutorial:
# https://regexone.com/references/python
# In[51]:
import re
# **TIP**: Use [Pythex.org](https://pythex.org/) to try out your regular expression
#
# Example on Pythex: click here
# **Example 1:**
# In[52]:
string_1 = 'Ties de Kok (#IDNUMBER: 123-AZ). Rest of text...'
string_2 = 'Philip Joos (#IDNUMBER: 663-BY). Rest of text...'
# In[53]:
pattern = r'#IDNUMBER: (\d\d\d-\w\w)'
# In[54]:
print(re.findall(pattern, string_1)[0])
print(re.findall(pattern, string_2)[0])
# ### Example 2:
# If a sentence contains the word 'million' return True, otherwise return False
# In[55]:
for sen in spacy_text_clean['TimFarrand'][2]:
TERM = 'million'
if re.search('million', sen, flags= re.IGNORECASE):
print(sen)
# ## Text evaluation [(to top)](#toc)
# Besides feature search there are also many ways to analyze the text as a whole.
#
# Let's, for example, evaluate the following paragraph:
# In[56]:
example_paragraph = ' '.join([x for x in spacy_text_clean['TimFarrand'][2]])
example_paragraph[:500]
# ### Language [(to top)](#toc)
# Using the `spacy-langdetect` package it is easy to detect the language of a piece of text
# In[57]:
from spacy_langdetect import LanguageDetector
nlp.add_pipe(LanguageDetector(), name='language_detector', last=True)
# In[58]:
print(nlp(example_paragraph)._.language)
# ### Readability [(to top)](#toc)
# Generally I'd recommend to calculate the readability metrics by yourself as they don't tend to be that difficult to compute. However, there are packages out there that can help, such as `spacy_readability`
# In[59]:
from spacy_readability import Readability
# In[60]:
nlp.add_pipe(Readability(), name='readability', last=True)
# In[61]:
doc = nlp("I am some really difficult text to read because I use obnoxiously large words.")
print(doc._.flesch_kincaid_grade_level)
print(doc._.smog)
# **Manual example:** FOG index
# In[62]:
import syllapy
# In[63]:
def calculate_fog(document):
doc = nlp(document, disable=['tagger', 'ner', 'entity_linker', 'textcat', 'entitry_ruler'])
sen_list = list(doc.sents)
num_sen = len(sen_list)
num_words = 0
num_complex_words = 0
for sen_obj in sen_list:
words_in_sen = [token.text for token in sen_obj if token.is_alpha]
num_words += len(words_in_sen)
num_complex = 0
for word in words_in_sen:
num_syl = syllapy.count(word.lower())
if num_syl > 2:
num_complex += 1
num_complex_words += num_complex
fog = 0.4 * ((num_words / num_sen) + ((num_complex_words / num_words)*100))
return {'fog' : fog,
'num_sen' : num_sen,
'num_words' : num_words,
'num_complex_words' : num_complex_words}
# In[64]:
calculate_fog(example_paragraph)
# ## Text similarity
# ### Using `fuzzywuzzy`
# In[65]:
from fuzzywuzzy import fuzz
# In[66]:
fuzz.ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")
# ### Using `spacy`
# Spacy can provide a similary score based on the semantic similarity ([link](https://spacy.io/usage/vectors-similarity))
# In[67]:
tokens_1 = nlp("fuzzy wuzzy was a bear")
tokens_2 = nlp("wuzzy fuzzy was a bear")
tokens_1.similarity(tokens_2)
# In[68]:
tokens_1 = nlp("Tom believes German cars are the best.")
tokens_2 = nlp("Sarah recently mentioned that she would like to go on holiday to Germany.")
tokens_1.similarity(tokens_2)
# ### Term (dictionary) counting [(to top)](#toc)
# A common technique for basic NLP insights is to create simple metrics based on term counts.
#
# These are relatively easy to implement.
# ### Example 1:
# In[69]:
word_dictionary = ['soft', 'first', 'most', 'be']
# In[70]:
for word in word_dictionary:
print(word, example_paragraph.count(word))
# ### Example 2:
# In[71]:
pos = ['great', 'agree', 'increase']
neg = ['bad', 'disagree', 'decrease']
sentence = '''According to the president everything is great, great,
and great even though some people might disagree with those statements.'''
pos_count = 0
for word in pos:
pos_count += sentence.lower().count(word)
print(pos_count)
neg_count = 0
for word in neg:
neg_count += sentence.lower().count(word)
print(neg_count)
pos_count / (neg_count + pos_count)
# Getting the total number of words is also easy:
# In[72]:
num_tokens = len([token for token in nlp(sentence) if token.is_alpha])
num_tokens
# #### Example 3:
# We can also save the count per word
# In[73]:
pos_count_dict = {}
for word in pos:
pos_count_dict[word] = sentence.lower().count(word)
# In[74]:
pos_count_dict
# *Note:* `.lower()` is actually quite slow, if you have a lot of words / sentences it is recommend to minimize the amount of `.lower()` operations that you have to make.
# # Represent text numerically [(to top)](#toc)
# ## Bag of Words [(to top)](#toc)
# Sklearn includes the `CountVectorizer` and `TfidfVectorizer` function.
#
# For details, see the documentation:
# [TF](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer)
# [TFIDF](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html#sklearn.feature_extraction.text.TfidfVectorizer)
#
# *Note 1:* these functions also provide a variety of built-in preprocessing options (e.g. ngrames, remove stop words, accent stripper).
#
# *Note 2:* example based on the following website [click here](http://ethen8181.github.io/machine-learning/clustering_old/tf_idf/tf_idf.html)
# In[75]:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
# ### Simple example:
# In[76]:
doc_1 = "The sky is blue."
doc_2 = "The sun is bright today."
doc_3 = "The sun in the sky is bright."
doc_4 = "We can see the shining sun, the bright sun."
# Calculate term frequency:
# In[77]:
vectorizer = CountVectorizer(stop_words='english')
tf = vectorizer.fit_transform([doc_1, doc_2, doc_3, doc_4])
# In[78]:
print(vectorizer.get_feature_names(), '\n')
for doc_tf_vector in tf.toarray():
print(doc_tf_vector)
# ### TF-IDF [(to top)](#toc)
# In[79]:
transformer = TfidfVectorizer(stop_words='english')
tfidf = transformer.fit_transform([doc_1, doc_2, doc_3, doc_4])
# In[80]:
for doc_vector in tfidf.toarray():
print(doc_vector)
# ### More elaborate example:
# In[81]:
clean_paragraphs = []
for author, value in spacy_text_clean.items():
for article in value:
clean_paragraphs.append(' '.join([x for x in article]))
# In[82]:
len(clean_paragraphs)
# In[83]:
transformer = TfidfVectorizer(stop_words='english')
tfidf_large = transformer.fit_transform(clean_paragraphs)
# In[84]:
print('Number of vectors:', len(tfidf_large.toarray()))
print('Number of words in dictionary:', len(tfidf_large.toarray()[0]))
# In[85]:
tfidf_large
# ## Word Embeddings [(to top)](#toc)
# ### Spacy [(to top)](#toc)
# The `en_core_web_lg` language model comes with GloVe vectors trained on the Common Crawl dataset ([link](https://spacy.io/models/en#en_core_web_lg))
# In[86]:
tokens = nlp("The Dutch word for peanut butter is 'pindakaas', did you know that? This is a typpo.")
for token in tokens:
if token.is_alpha:
print(token.text, token.has_vector, token.vector_norm, token.is_oov)
# In[87]:
token = nlp('Car')
print('The token: "{}" has the following vector (dimension: {})'.format(token.text, len(token.vector)))
token.vector
# ### Word2Vec [(to top)](#toc)
# Simple example below is from: https://medium.com/@mishra.thedeepak/word2vec-in-minutes-gensim-nlp-python-6940f4e00980
# *Note:* you might have to run `nltk.download('brown')` to install the NLTK corpus files
# In[88]:
import gensim
from nltk.corpus import brown
# In[89]:
sentences = brown.sents()
# In[90]:
model = gensim.models.Word2Vec(sentences, min_count=1)
# Save model
# In[91]:
model.save('brown_model')
# Load model
# In[92]:
model = gensim.models.Word2Vec.load('brown_model')
# Find words most similar to 'mother':
# In[93]:
print(model.wv.most_similar("mother"))
# Find the odd one out:
# In[94]:
print(model.wv.doesnt_match("breakfast cereal dinner lunch".split()))
# In[95]:
print(model.wv.doesnt_match("pizza pasta garden fries".split()))
# Retrieve vector representation of the word "human"
# In[96]:
model.wv['human']
# # Statistical models [(to top)](#toc)
# ## "Traditional" machine learning [(to top)](#toc)
# The library to use for machine learning is scikit-learn (["sklearn"](http://scikit-learn.org/stable/index.html)).
# ## Supervised [(to top)](#toc)
# In[97]:
from sklearn.model_selection import cross_val_score, KFold, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics
import joblib
# In[98]:
import pandas as pd
import numpy as np
# ### Convert the data into a pandas dataframe (so that we can input it easier)
# In[99]:
article_list = []
for author, value in spacy_text_clean.items():
for article in value:
article_list.append((author, ' '.join([x for x in article])))
# In[100]:
article_df = pd.DataFrame(article_list, columns=['author', 'text'])
# In[101]:
article_df.sample(5)
# ### Split the sample into a training and test sample
# In[102]:
X_train, X_test, y_train, y_test = train_test_split(article_df.text, article_df.author, test_size=0.20, random_state=3561)
# In[103]:
print(len(X_train), len(X_test))
# ### Train and evaluate function
# Simple function to train (i.e. fit) and evaluate the model
# In[104]:
def train_and_evaluate(clf, X_train, X_test, y_train, y_test):
clf.fit(X_train, y_train)
print("Accuracy on training set:")
print(clf.score(X_train, y_train))
print("Accuracy on testing set:")
print(clf.score(X_test, y_test))
y_pred = clf.predict(X_test)
print("Classification Report:")
print(metrics.classification_report(y_test, y_pred))
# ### Naïve Bayes estimator [(to top)](#toc)
# In[105]:
from sklearn.naive_bayes import MultinomialNB
# Define pipeline
# In[106]:
clf = Pipeline([
('vect', TfidfVectorizer(strip_accents='unicode',
lowercase = True,
max_features = 1500,
stop_words='english'
)),
('clf', MultinomialNB(alpha = 1,
fit_prior = True
)
),
])
# Train and show evaluation stats
# In[107]:
train_and_evaluate(clf, X_train, X_test, y_train, y_test)
# Save results
# In[108]:
joblib.dump(clf, 'naive_bayes_results.pkl')
# Predict out of sample:
# In[109]:
example_y, example_X = y_train[33], X_train[33]
# In[110]:
print('Actual author:', example_y)
print('Predicted author:', clf.predict([example_X])[0])
# ### Support Vector Machines (SVM) [(to top)](#toc)
# In[111]:
from sklearn.svm import SVC
# Define pipeline
# In[112]:
clf_svm = Pipeline([
('vect', TfidfVectorizer(strip_accents='unicode',
lowercase = True,
max_features = 1500,
stop_words='english'
)),
('clf', SVC(kernel='rbf' ,
C=10, gamma=0.3)
),
])
# *Note:* The SVC estimator is very sensitive to the hyperparameters!
# Train and show evaluation stats
# In[113]:
train_and_evaluate(clf_svm, X_train, X_test, y_train, y_test)
# Save results
# In[114]:
joblib.dump(clf_svm, 'svm_results.pkl')
# Predict out of sample:
# In[115]:
example_y, example_X = y_train[33], X_train[33]
# In[116]:
print('Actual author:', example_y)
print('Predicted author:', clf_svm.predict([example_X])[0])
# ## Model Selection and Evaluation [(to top)](#toc)
# Both the `TfidfVectorizer` and `SVC()` estimator take a lot of hyperparameters.
#
# It can be difficult to figure out what the best parameters are.
#
# We can use `GridSearchCV` to help figure this out.
# In[117]:
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer
from sklearn.metrics import f1_score
# First we define the options that should be tried out:
# In[118]:
clf_search = Pipeline([
('vect', TfidfVectorizer()),
('clf', SVC())
])
parameters = { 'vect__stop_words': ['english'],
'vect__strip_accents': ['unicode'],
'vect__max_features' : [1500],
'vect__ngram_range': [(1,1), (2,2) ],
'clf__gamma' : [0.2, 0.3, 0.4],
'clf__C' : [8, 10, 12],
'clf__kernel' : ['rbf']
}
# Run everything:
# In[119]:
grid = GridSearchCV(clf_search,
param_grid=parameters,
scoring=make_scorer(f1_score, average='micro'),
n_jobs=-1
)
grid.fit(X_train, y_train)
# *Note:* if you are on a powerful (preferably unix system) you can set n_jobs to the number of available threads to speed up the calculation
# In[120]:
print("The best parameters are %s with a score of %0.2f" % (grid.best_params_, grid.best_score_))
y_true, y_pred = y_test, grid.predict(X_test)
print(metrics.classification_report(y_true, y_pred))
# ## Unsupervised [(to top)](#toc)
# ### Latent Dirichilet Allocation (LDA) [(to top)](#toc)
# In[121]:
from sklearn.decomposition import LatentDirichletAllocation
# Vectorizer (using countvectorizer for the sake of example)
# In[122]:
vectorizer = CountVectorizer(strip_accents='unicode',
lowercase = True,
max_features = 1500,
stop_words='english', max_df=0.8)
tf_large = vectorizer.fit_transform(clean_paragraphs)
# Run the LDA model
# In[123]:
n_topics = 10
n_top_words = 25
# In[124]:
lda = LatentDirichletAllocation(n_components=n_topics, max_iter=10,
learning_method='online',
n_jobs=-1)
lda_fitted = lda.fit_transform(tf_large)
# Visualize top words
# In[125]:
def save_top_words(model, feature_names, n_top_words):
out_list = []
for topic_idx, topic in enumerate(model.components_):
out_list.append((topic_idx+1, " ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]])))
out_df = pd.DataFrame(out_list, columns=['topic_id', 'top_words'])
return out_df
# In[126]:
result_df = save_top_words(lda, vectorizer.get_feature_names(), n_top_words)
# In[127]:
result_df
# ### pyLDAvis [(to top)](#toc)
# In[128]:
get_ipython().run_line_magic('matplotlib', 'inline')
import pyLDAvis
import pyLDAvis.sklearn
pyLDAvis.enable_notebook()
# In[129]:
pyLDAvis.sklearn.prepare(lda, tf_large, vectorizer, n_jobs=-1)
# **Warning:** there is a small bug that when you show the `pyLDAvis` visualization it will hide some of the icons of JupyterLab
# ## Neural Networks [(to top)](#toc)
# Interested? Check out the Stanford course CS224n ([Page](http://web.stanford.edu/class/cs224n/index.html#schedule))!