Author: Ties de Kok (Personal Website)
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
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:
This notebook only discusses step 3 and 4. If you want to learn more about step 2 see my Python tutorial.
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
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:
Spacy
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:
scikit learn
Specific task libraries:
There are many, just a couple of examples:
pyLDAvis
for visualizing LDA)langdetect
for detecting languagesfuzzywuzzy
for fuzzy text matchingGensim
for topic modellingThere 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
Can't follow what I am doing here? Please see my Python tutorial (although the zipfile
and io
operations are not very relevant).
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
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
folder_dict = {'test' : 'C50test'}
text_dict = {'test' : {}}
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()))
HBox(children=(FloatProgress(value=0.0, max=1.0), HTML(value='')))
Note: the text comes pre-split per sentence, for the sake of example I undo this through ' '.join(text_file.readlines()
text_dict['test']['TimFarrand'][0]
'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 Commission which is due to report before March 24, 1997. The shares fell 6p to 781p on the news.\n "The stock is probably dead in the water until March," said John Wakley, analyst at Lehman Brothers. \n Dermott Carr, an analyst at Nikko said, "the market is going to hang onto them for the moment but until we get a decision they will be held back."\n Whatever the MMC decides many analysts expect Lang to defer a decision until after the next general election which will be called by May 22.\n "They will probably try to defer the decision until after the election. I don\'t think they want the negative PR of having a large number of people fired," said Wakley. \n If the deal does not go through, analysts calculate the maximum loss to Bass of 60 million, with most sums centred on the 30-40 million range.\n "It\'s a maxiumum loss of 60 million for Bass if they fail and, unlike Allied, you would have to compare it to the perceived upside of doing the deal," said Wakley.\n Bass said at the time of the deal it would take a one-off charge of 75 million stg for restructuring the combined business, resulting in expected annual cost savings of 90 million stg within three years. \n Under the terms of the complex deal, if Bass cannot combine C-T with its own brewing business within 16 months, it has the option to put its whole shareholding to Carlsberg for 110 million stg and Carlsberg has an option to put 15 percent of C-T to Allied Domecq, which would reimburse Bass 30 million stg.\n Bass is also entitled to receive 50 percent of all profits earnied by C-T until the merger is complete, which should give it some 30-35 million stg in a full year. Carlsberg has agreed to contribute its interests and 20 million stg in exchange for a 20 percent share in the combined Bass Breweries and Carlsberg-Tetley business.\n C-T was a joint venture between Allied Domecq and Carlsberg formed in 1992 by the merger of their UK brewing and wholesaleing businesses.\n -- London Newsroom +44 171 542 6437\n'
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.
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()
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()
:
spacy_text = {}
for author, text_list in tqdm(text_dict['test'].items()):
spacy_text[author] = list(nlp.pipe(text_list))
HBox(children=(FloatProgress(value=0.0, max=50.0), HTML(value='')))
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
type(spacy_text['TimFarrand'][0])
spacy.tokens.doc.Doc
import nltk
We can apply basic nltk
operations directly to the text so we don't need to convert first.
from textblob import TextBlob
Convert all text in the "test" sample to a TextBlob
object using TextBlob()
:
textblob_text = {}
for author, text_list in text_dict['test'].items():
textblob_text[author] = [TextBlob(text) for text in text_list]
type(textblob_text['TimFarrand'][0])
textblob.blob.TextBlob
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:
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:
text_dict['test']['TimFarrand'][0][:298]
"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"
print(text_dict['test']['TimFarrand'][0][:298])
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. Earlier Lang announced the Bass deal would be referred to the Monoplies and Mergers
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:
text_dict['test']['TimFarrand'][0][:298].replace('\n', '').replace('\\', '')
"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. Earlier Lang announced the Bass deal would be referred to the Monoplies and Mergers"
Sometimes, however, the problem arrises because of encoding / decoding problems.
In those cases you can usually do something like:
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'))
This is some π text that has to be cleaned…! it's difficult to deal with! b"This is some text that has to be cleaned! it's difficult to deal with!"
An alternative that is better at preserving the unicode characters would be to use unidecode
import unidecode
print('\u738b\u7389')
王玉
unidecode.unidecode(u"\u738b\u7389")
'Wang Yu '
unidecode.unidecode(problem_sentence)
"This is some p text that has to be cleaned...! it's difficult to deal with!"
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:
text_dict['test']['TimFarrand'][0][:550].split('.')
["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 Commission which is due to report before March 24, 1997', ' The shares fell 6p to 781p on the news', '\n "The stock is probably dead in the water until March," said John Wakley, analyst at Lehman Brothers', ' \n Dermott Carr, an analyst at Nikko said, "the mark']
It is better to use a more sophisticated implementation such as the one by Spacy
:
example_paragraph = spacy_text['TimFarrand'][0]
sentence_list = [s for s in example_paragraph.sents]
sentence_list[:5]
[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. , Earlier Lang announced the Bass deal would be referred to the Monoplies and Mergers Commission which is due to report before March 24, 1997., The shares fell 6p to 781p on the news. , "The stock is probably dead in the water until March," said John Wakley, analyst at Lehman Brothers. , Dermott Carr, an analyst at Nikko said, "the market is going to hang onto them for the moment]
Notice that the returned object is still a spacy
object:
type(sentence_list[0])
spacy.tokens.span.Span
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):
spacy_sentences = {}
for author, text_list in tqdm(spacy_text.items()):
spacy_sentences[author] = [list(text.sents) for text in text_list]
HBox(children=(FloatProgress(value=0.0, max=50.0), HTML(value='')))
spacy_sentences['TimFarrand'][0][:3]
[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. , Earlier Lang announced the Bass deal would be referred to the Monoplies and Mergers Commission which is due to report before March 24, 1997., The shares fell 6p to 781p on the news. ]
Word tokenization means to split the sentence (or text) up into words.
example_sentence = spacy_sentences['TimFarrand'][0][0]
example_sentence
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.
A word is called a token
in this context (hence tokenization
), using spacy
:
token_list = [token for token in example_sentence]
token_list[0:15]
[Shares, in, brewing, -, to, -, leisure, group, Bass, Plc, are, likely, to, be, held]
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:
lemmatized = [token.lemma_ for token in example_sentence]
lemmatized[0:15]
['share', 'in', 'brewing', '-', 'to', '-', 'leisure', 'group', 'Bass', 'Plc', 'be', 'likely', 'to', 'be', 'hold']
NLTK
Using the NLTK libary we can also use the more aggressive Porter Stemmer
from nltk.stem.porter import PorterStemmer
stemmer = PorterStemmer()
stemmed = [stemmer.stem(token.text) for token in example_sentence]
stemmed[0:15]
['share', 'in', 'brew', '-', 'to', '-', 'leisur', 'group', 'bass', 'plc', 'are', 'like', 'to', 'be', 'held']
Compare:
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, ' '))
Original | Spacy Lemma | NLTK Stemmer ----------------------------------------- Shares | share | share in | in | in brewing | brewing | brew - | - | - to | to | to - | - | - leisure | leisure | leisur group | group | group Bass | Bass | bass Plc | Plc | plc are | be | are likely | likely | like to | to | to be | be | be held | hold | held
In my experience it is usually best to use lemmatization instead of a stemmer.
Text is inherently structured in complex ways, we can often use some of this underlying structure.
Part of speech tagging refers to the identification of words as nouns, verbs, adjectives, etc.
Using Spacy
:
pos_list = [(token, token.pos_) for token in example_sentence]
pos_list[0:10]
[(Shares, 'NOUN'), (in, 'ADP'), (brewing, 'NOUN'), (-, 'PUNCT'), (to, 'ADP'), (-, 'PUNCT'), (leisure, 'NOUN'), (group, 'NOUN'), (Bass, 'PROPN'), (Plc, 'PROPN')]
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
Using NLTK
:
bigram_list = ['-'.join(x) for x in nltk.bigrams([token.text for token in example_sentence])]
bigram_list[10:15]
['are-likely', 'likely-to', 'to-be', 'be-held', 'held-back']
Using spacy
def tokenize_without_punctuation(sen_obj):
return [token.text for token in sen_obj if token.is_alpha]
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
create_ngram(example_sentence, 2)[:5]
['Shares-in', 'in-brewing', 'brewing-to', 'to-leisure', 'leisure-group']
create_ngram(example_sentence, 3)[:5]
['Shares-in-brewing', 'in-brewing-to', 'brewing-to-leisure', 'to-leisure-group', 'leisure-group-Bass']
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
:
no_stop_words = [token for token in example_sentence if not token.is_stop]
no_stop_words[:10]
[Shares, brewing, -, -, leisure, group, Bass, Plc, likely, held]
token_list[:10]
[Shares, in, brewing, -, to, -, leisure, group, Bass, Plc]
Note we can also remove punctuation in the same way:
[token for token in example_sentence if not token.is_stop and token.is_alpha][:10]
[Shares, brewing, leisure, group, Bass, Plc, likely, held, Britain, Trade]
Basic SpaCy text processing function
textacy
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]
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
HBox(children=(FloatProgress(value=0.0, max=50.0), HTML(value='')))
Note: that this would take quite a long time if we didn't disable some of the components.
count = 0
for author, texts in spacy_text_clean.items():
for text in texts:
count += len(text)
print('Number of sentences:', count)
Number of sentences: 58973
Result
spacy_text_clean['TimFarrand'][0][:3]
['Shares brew leisure group Bass Plc likely hold Britain Trade Industry secretary Ian Lang decide allow propose merge brewer Carlsberg Tetley say analyst', 'Earlier Lang announce Bass deal refer Monoplies Mergers Commission report March', 'share fall news']
Note: the quality of the input text is not great, so the sentence segmentation is also not great (without further tweaking).
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.
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.
example_sentence = spacy_sentences['TimFarrand'][0][3]
example_sentence
"The stock is probably dead in the water until March," said John Wakley, analyst at Lehman Brothers.
[(i, i.label_) for i in nlp(example_sentence.text).ents]
[(March, 'DATE'), (John Wakley, 'PERSON'), (Lehman Brothers, 'ORG')]
example_sentence = spacy_sentences['TimFarrand'][4][0]
example_sentence
British pub-to-hotel group Greenalls Plc on Thursday reported a 48 percent rise in profits before exceptional items to 148.7 million pounds ($246.4 million), driven by its acquisition of brewer Boddington in November 1995.
[(i, i.label_) for i in nlp(example_sentence.text).ents]
[(British, 'NORP'), (Greenalls Plc, 'ORG'), (Thursday, 'DATE'), (48 percent, 'PERCENT'), (148.7 million pounds, 'MONEY'), ($246.4 million, 'MONEY'), (Boddington, 'ORG'), (November 1995, 'DATE')]
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
import re
TIP: Use Pythex.org to try out your regular expression
Example on Pythex: click here
Example 1:
string_1 = 'Ties de Kok (#IDNUMBER: 123-AZ). Rest of text...'
string_2 = 'Philip Joos (#IDNUMBER: 663-BY). Rest of text...'
pattern = r'#IDNUMBER: (\d\d\d-\w\w)'
print(re.findall(pattern, string_1)[0])
print(re.findall(pattern, string_2)[0])
123-AZ 663-BY
If a sentence contains the word 'million' return True, otherwise return False
for sen in spacy_text_clean['TimFarrand'][2]:
TERM = 'million'
if re.search('million', sen, flags= re.IGNORECASE):
print(sen)
Analysts forecast pretax profit range million stg restructure cost million time restructure cost million anticipate bulk million stem closure small production plant France Cadbury drink business turn million stg trade profit million half entirely contribution Dr Pepper Campbell estimate UK beverage contribute million stg operate profit million time Broadly analyst expect pretty flat performance group confectionery business consensus forecast million stg operate profit average analyst calculate beverage chip trade profit million sale percent stake Coca Cola amp Schweppes Beverages CCSB operation Coca Cola Enterprises June million stg analyst want clear statement strategy company far analyst company say shareholder expect return investment emerge market large far million Russian plant Cadbury announce investment million stg build new plant Wrocoaw Poland joint venture China cost million Net debt billion end fall million end result CCSB sale provide acquisition
Besides feature search there are also many ways to analyze the text as a whole.
Let's, for example, evaluate the following paragraph:
example_paragraph = ' '.join([x for x in spacy_text_clean['TimFarrand'][2]])
example_paragraph[:500]
'Soft drink confectionery group Cadbury Schweppes Plc expect report solid percent rise half profit Wednesday face question performance soft drink main question success relaunch brand say Mark Duffy food manufacture analyst SBC Warburg Competitor Sprite own Coca Cola see agressive market push rank fast grow brand Cadbury Dr Pepper Analysts forecast pretax profit range million stg restructure cost million time dividend penny expect restructure cost million anticipate bulk million stem closure small'
Using the spacy-langdetect
package it is easy to detect the language of a piece of text
from spacy_langdetect import LanguageDetector
nlp.add_pipe(LanguageDetector(), name='language_detector', last=True)
print(nlp(example_paragraph)._.language)
{'language': 'en', 'score': 0.9999970401265338}
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
from spacy_readability import Readability
nlp.add_pipe(Readability(), name='readability', last=True)
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)
8.412857142857145 0
Manual example: FOG index
import syllapy
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}
calculate_fog(example_paragraph)
{'fog': 13.42327889849504, 'num_sen': 36, 'num_words': 347, 'num_complex_words': 83}
fuzzywuzzy
¶from fuzzywuzzy import fuzz
fuzz.ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear")
91
spacy
¶Spacy can provide a similary score based on the semantic similarity (link)
tokens_1 = nlp("fuzzy wuzzy was a bear")
tokens_2 = nlp("wuzzy fuzzy was a bear")
tokens_1.similarity(tokens_2)
1.0000000623731768
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)
0.8127869114665882
A common technique for basic NLP insights is to create simple metrics based on term counts.
These are relatively easy to implement.
word_dictionary = ['soft', 'first', 'most', 'be']
for word in word_dictionary:
print(word, example_paragraph.count(word))
soft 2 first 0 most 0 be 7
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)
4 1
0.8
Getting the total number of words is also easy:
num_tokens = len([token for token in nlp(sentence) if token.is_alpha])
num_tokens
19
We can also save the count per word
pos_count_dict = {}
for word in pos:
pos_count_dict[word] = sentence.lower().count(word)
pos_count_dict
{'great': 3, 'agree': 1, 'increase': 0}
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.
Sklearn includes the CountVectorizer
and TfidfVectorizer
function.
For details, see the documentation:
TF
TFIDF
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
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
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:
vectorizer = CountVectorizer(stop_words='english')
tf = vectorizer.fit_transform([doc_1, doc_2, doc_3, doc_4])
print(vectorizer.get_feature_names(), '\n')
for doc_tf_vector in tf.toarray():
print(doc_tf_vector)
['blue', 'bright', 'shining', 'sky', 'sun', 'today'] [1 0 0 1 0 0] [0 1 0 0 1 1] [0 1 0 1 1 0] [0 1 1 0 2 0]
transformer = TfidfVectorizer(stop_words='english')
tfidf = transformer.fit_transform([doc_1, doc_2, doc_3, doc_4])
for doc_vector in tfidf.toarray():
print(doc_vector)
[0.78528828 0. 0. 0.6191303 0. 0. ] [0. 0.47380449 0. 0. 0.47380449 0.74230628] [0. 0.53256952 0. 0.65782931 0.53256952 0. ] [0. 0.36626037 0.57381765 0. 0.73252075 0. ]
clean_paragraphs = []
for author, value in spacy_text_clean.items():
for article in value:
clean_paragraphs.append(' '.join([x for x in article]))
len(clean_paragraphs)
2500
transformer = TfidfVectorizer(stop_words='english')
tfidf_large = transformer.fit_transform(clean_paragraphs)
print('Number of vectors:', len(tfidf_large.toarray()))
print('Number of words in dictionary:', len(tfidf_large.toarray()[0]))
Number of vectors: 2500 Number of words in dictionary: 21978
tfidf_large
<2500x21978 sparse matrix of type '<class 'numpy.float64'>' with 410121 stored elements in Compressed Sparse Row format>
The en_core_web_lg
language model comes with GloVe vectors trained on the Common Crawl dataset (link)
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)
The True 4.70935 False Dutch True 6.381229 False word True 5.8387117 False for True 4.8435082 False peanut True 7.085804 False butter True 7.466713 False is True 4.890306 False pindakaas False 0.0 False did True 5.284421 False you True 5.1979666 False know True 5.160699 False that True 4.8260193 False This True 5.0461264 False is True 4.890306 False a True 5.306696 False typpo False 0.0 True
token = nlp('Car')
print('The token: "{}" has the following vector (dimension: {})'.format(token.text, len(token.vector)))
token.vector
The token: "Car" has the following vector (dimension: 300)
array([ 2.0987e-01, 4.6481e-01, -2.4238e-01, -6.5751e-02, 6.0856e-01, -3.4698e-01, -2.5331e-01, -4.2590e-01, -2.2277e-01, 2.2913e+00, -3.3853e-01, 2.3275e-01, -2.7511e-01, 2.4064e-01, -1.0697e+00, -2.6978e-01, -8.0733e-01, 1.8698e+00, 4.5562e-01, -1.4469e-01, 1.6246e-02, -3.5473e-01, 7.6152e-01, -6.8589e-02, 1.2156e-02, 9.0520e-03, 1.1131e-01, -3.0746e-01, 2.4168e-01, 1.1400e-01, 4.3952e-01, -6.6594e-01, -7.3198e-02, 8.0566e-01, 1.1748e-01, -3.8758e-01, 1.0691e-01, 3.3697e-01, -1.3188e-01, 1.9364e-01, 5.5553e-01, -3.4029e-01, 1.7059e-01, 4.0736e-01, -1.6150e-01, 7.0302e-02, 6.7772e-02, -8.1763e-01, 3.0645e-01, -9.9862e-03, 9.4606e-02, -5.9763e-01, 1.4192e-01, 1.4857e-01, -3.1535e-01, 9.9092e-02, 2.0673e-01, -4.4041e-01, 2.1519e-01, -4.1294e-01, 2.6374e-01, -1.5493e-01, 2.4739e-01, 4.2090e-01, 1.8768e-01, 4.6904e-02, 9.6848e-02, 2.7431e-02, 1.0633e-01, 3.1926e-01, -7.6260e-01, -8.8373e-02, 3.7519e-01, 4.7369e-01, -7.3557e-01, -1.0760e-01, -2.6557e-02, -5.1079e-01, -1.8886e-01, 2.8679e-01, 6.5798e-02, 5.7129e-01, 2.5056e-01, 7.3858e-02, 8.4700e-03, 1.5158e-02, 7.3570e-01, 6.2549e-01, 5.1600e-02, -2.5802e-01, -8.1203e-02, 1.3731e-01, 1.8809e-01, -6.5871e-01, -2.2361e-01, -3.3318e-01, 1.5853e-01, 5.1523e-01, 5.0259e-01, -1.6894e-01, -8.6465e-02, 2.5036e-01, -1.7419e-01, -2.7723e-02, 1.1262e-01, -4.6449e-01, 1.6956e-01, 2.8931e-01, -1.3187e-01, 4.6368e-01, -2.9348e-01, -3.1244e-01, 6.5886e-01, -4.7842e-01, 1.4754e-01, -3.0646e-01, 4.3847e-01, 1.7684e-01, -1.1968e-01, -3.1002e-02, -1.2228e-01, -5.6424e-01, 1.5289e-01, -7.9389e-01, -3.6731e-01, 1.6918e-01, -9.5210e-02, 1.6490e-01, 1.5936e-01, 1.2460e-01, 3.8846e-01, 2.3019e-01, -1.3054e-01, -2.1932e-01, -2.6782e-01, -6.0745e-01, -3.4826e-01, 1.7656e-01, -1.0351e-01, -2.2750e-01, -1.6111e+00, -4.0504e-01, 1.0872e+00, -1.6391e-01, 6.5586e-02, -1.0632e-01, -1.4014e-01, 1.7712e-01, 7.1100e-01, 2.0313e-01, -5.0138e-01, 1.7291e-01, -5.3208e-02, -4.0668e-01, 1.4907e-01, -3.0631e-01, 4.6572e-01, 3.7977e-01, -1.3336e-01, -7.6937e-02, 1.1803e-02, -1.1185e-01, 7.0364e-01, -6.8615e-02, 5.8586e-01, -5.9890e-01, -2.8104e-01, 4.9674e-01, 4.5867e-01, 1.6291e-01, -2.8317e-01, 3.8870e-01, -3.9882e-01, 2.2407e-01, -2.3704e-01, -2.3155e-01, 6.7882e-02, 8.3828e-01, 1.3231e-01, 2.9778e-01, 1.8471e-01, -9.7415e-05, -6.9993e-01, 4.6959e-03, -3.5461e-01, -9.6413e-02, 1.0312e-01, 8.5293e-02, -2.6909e-01, 4.3886e-01, 3.1275e-01, 2.2829e-01, 4.8072e-01, 1.8399e-01, -1.7628e-01, -4.8322e-01, 9.5676e-02, -2.4499e-01, 5.8915e-02, -3.9355e-02, -4.6954e-01, -2.6272e-01, 1.5462e-01, -1.8055e-01, 1.6881e-03, 5.7027e-02, -6.7284e-02, 2.4853e-01, 3.5735e-01, 1.4325e-01, -4.9276e-01, -2.9321e-02, 5.1167e-02, 4.9620e-01, 3.7308e-01, 4.0203e-01, 9.2905e-02, 7.4061e-01, -3.3765e-01, -3.5641e-01, 6.1675e-01, -9.5517e-01, -2.7492e-01, 2.2079e-01, -2.8898e-01, -1.5504e-01, -3.1433e-01, 5.8383e-01, -2.6138e-02, -2.7755e-01, -4.7184e-02, 1.0504e-01, -4.2419e-01, -1.6414e-01, -5.0711e-01, 4.2617e-01, 3.6889e-01, 4.3267e-01, -4.4480e-03, 5.6442e-01, -3.0964e-02, 7.7629e-02, 2.2218e-01, 1.2818e-01, -1.6235e-01, -2.2912e-01, 4.9174e-01, -5.1937e-01, -2.0793e-01, -3.6868e-01, -5.5714e-01, -1.9930e-01, 2.9782e-01, 7.5921e-02, -3.9895e-01, 8.1692e-01, -1.0221e-01, -3.8049e-01, 1.9906e-01, -1.9875e-02, 7.3431e-02, -1.3882e-01, 2.7914e-01, -4.5367e-01, 2.9227e-01, -5.5489e-01, -4.2121e-01, 5.5667e-01, -4.5230e-01, -1.1956e-01, 1.3504e-01, -2.3580e-01, 7.4221e-01, -2.7890e-01, -5.4580e-02, 3.1944e-01, 3.6717e-01, 1.3430e-01, 1.3629e-01, -9.7458e-02, -6.0310e-01, -1.7762e-01, 2.5910e-01, 3.3150e-01, 2.2701e-01, 6.3664e-01, 1.5324e-01, -3.2894e-01, -3.6749e-01, -2.0328e-01, -1.1924e+00, -4.6395e-01, 6.6984e-01, -4.9404e-01, 4.4154e-01, -4.3699e-01, 2.3538e-01, 3.2135e-01, 2.6649e-01, 2.2438e-01], dtype=float32)
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
import gensim
from nltk.corpus import brown
sentences = brown.sents()
model = gensim.models.Word2Vec(sentences, min_count=1)
Save model
model.save('brown_model')
Load model
model = gensim.models.Word2Vec.load('brown_model')
Find words most similar to 'mother':
print(model.wv.most_similar("mother"))
[('father', 0.9847322702407837), ('husband', 0.9656894207000732), ('wife', 0.9496790170669556), ('friend', 0.9323333501815796), ('son', 0.9279097318649292), ('nickname', 0.9207977652549744), ('eagle', 0.9097722768783569), ('addiction', 0.9071668982505798), ('voice', 0.9051918983459473), ('patient', 0.8966456055641174)]
Find the odd one out:
print(model.wv.doesnt_match("breakfast cereal dinner lunch".split()))
cereal
D:\anaconda\envs\limpergPython\lib\site-packages\gensim\models\keyedvectors.py:877: FutureWarning: arrays to stack must be passed as a "sequence" type such as list or tuple. Support for non-sequence iterables such as generators is deprecated as of NumPy 1.16 and will raise an error in the future. vectors = vstack(self.word_vec(word, use_norm=True) for word in used_words).astype(REAL)
print(model.wv.doesnt_match("pizza pasta garden fries".split()))
garden
Retrieve vector representation of the word "human"
model.wv['human']
array([-0.40230748, -0.36424252, 0.48136342, 0.37950972, 0.25889766, -0.10284429, 0.2539682 , -0.557558 , -1.0109891 , -0.30390584, 0.02308058, -0.9227236 , 0.06572528, -0.24571045, -0.17627639, 0.35974783, -0.29690138, -0.25977215, 0.465111 , -1.5026555 , 0.23448153, -0.79958564, -0.6682266 , -0.51277363, -0.11112369, -1.4914587 , -0.30484447, 1.3466982 , -0.45936054, 0.02780625, 0.31517667, -0.12471037, 0.46333146, -0.29451668, 0.28516975, 1.3195679 , 0.02986159, 0.27836317, -0.5356812 , -0.5574794 , 0.55741835, -0.3692916 , 0.3067411 , -0.62016165, 0.6085465 , 0.6336735 , 0.9925447 , -0.2553504 , -0.3593044 , -0.29228973, -0.05774796, -0.22645272, -0.594325 , -0.19128117, 0.13758877, 0.58251387, -0.12266693, -0.33289537, -0.81493866, 0.64220285, -0.40921453, 1.7995448 , 0.98320687, 0.66162825, -0.03371862, 0.30391327, 0.30519032, -0.02499808, 0.46001107, -0.5412774 , -0.14508785, 0.47390515, -0.01815019, 0.39801887, 0.33498788, -0.70357895, 0.80516887, 0.08044272, -0.70585257, -0.7256744 , -0.95714486, -0.12571876, -0.20877206, -0.456315 , 0.7478423 , -0.25637153, 0.78873783, 0.24834621, 0.4455648 , 0.1293853 , 0.17152755, -0.30077967, 0.5803442 , 0.16445744, 0.60369337, -0.2301575 , -0.19547687, -0.36981392, 0.23723377, 0.24412107], dtype=float32)
The library to use for machine learning is scikit-learn ("sklearn").
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
import pandas as pd
import numpy as np
article_list = []
for author, value in spacy_text_clean.items():
for article in value:
article_list.append((author, ' '.join([x for x in article])))
article_df = pd.DataFrame(article_list, columns=['author', 'text'])
article_df.sample(5)
author | text | |
---|---|---|
1325 | LydiaZajc | Canadian unit Wal Mart Stores Inc bow Canadian... |
1516 | MarkBendeich | Australia labour market watchdog expect award ... |
2121 | SarahDavison | Temperatures rise Hong Kong prepare midsummer ... |
2226 | SimonCowell | British composite insurer Commercial Union Plc... |
1914 | PierreTran | French defence electronic firm Thomson CSF soo... |
X_train, X_test, y_train, y_test = train_test_split(article_df.text, article_df.author, test_size=0.20, random_state=3561)
print(len(X_train), len(X_test))
2000 500
Simple function to train (i.e. fit) and evaluate the model
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))
from sklearn.naive_bayes import MultinomialNB
Define pipeline
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
train_and_evaluate(clf, X_train, X_test, y_train, y_test)
Accuracy on training set: 0.8345 Accuracy on testing set: 0.72 Classification Report: precision recall f1-score support AaronPressman 0.82 1.00 0.90 9 AlanCrosby 0.55 0.92 0.69 12 AlexanderSmith 0.86 0.60 0.71 10 BenjaminKangLim 0.75 0.27 0.40 11 BernardHickey 0.75 0.30 0.43 10 BradDorfman 0.80 1.00 0.89 8 DarrenSchuettler 0.58 0.78 0.67 9 DavidLawder 1.00 0.60 0.75 10 EdnaFernandes 1.00 0.67 0.80 9 EricAuchard 0.86 0.67 0.75 9 FumikoFujisaki 1.00 1.00 1.00 10 GrahamEarnshaw 0.59 1.00 0.74 10 HeatherScoffield 0.83 0.56 0.67 9 JanLopatka 0.38 0.33 0.35 9 JaneMacartney 0.33 0.60 0.43 10 JimGilchrist 0.73 1.00 0.84 8 JoWinterbottom 0.90 0.90 0.90 10 JoeOrtiz 0.80 0.89 0.84 9 JohnMastrini 0.83 0.29 0.43 17 JonathanBirt 0.53 1.00 0.70 8 KarlPenhaul 0.87 1.00 0.93 13 KeithWeir 0.69 0.90 0.78 10 KevinDrawbaugh 0.88 0.70 0.78 10 KevinMorrison 0.33 1.00 0.50 3 KirstinRidley 0.86 0.67 0.75 9 KouroshKarimkhany 0.54 0.88 0.67 8 LydiaZajc 0.90 0.90 0.90 10 LynneO'Donnell 0.89 0.73 0.80 11 LynnleyBrowning 0.93 1.00 0.96 13 MarcelMichelson 1.00 0.50 0.67 12 MarkBendeich 0.86 0.55 0.67 11 MartinWolk 0.57 0.80 0.67 5 MatthewBunce 1.00 0.86 0.92 14 MichaelConnor 0.83 0.77 0.80 13 MureDickie 0.44 0.40 0.42 10 NickLouth 0.83 1.00 0.91 10 PatriciaCommins 0.80 0.89 0.84 9 PeterHumphrey 0.35 0.89 0.50 9 PierreTran 0.56 0.83 0.67 6 RobinSidel 1.00 1.00 1.00 12 RogerFillion 1.00 0.88 0.93 8 SamuelPerry 0.78 0.50 0.61 14 SarahDavison 1.00 0.29 0.44 14 ScottHillis 0.44 0.44 0.44 9 SimonCowell 0.91 1.00 0.95 10 TanEeLyn 1.00 0.57 0.73 7 TheresePoletti 0.80 0.73 0.76 11 TimFarrand 1.00 0.77 0.87 13 ToddNissen 0.60 1.00 0.75 9 WilliamKazer 0.00 0.00 0.00 10 accuracy 0.72 500 macro avg 0.75 0.74 0.71 500 weighted avg 0.77 0.72 0.71 500
Save results
joblib.dump(clf, 'naive_bayes_results.pkl')
['naive_bayes_results.pkl']
Predict out of sample:
example_y, example_X = y_train[33], X_train[33]
print('Actual author:', example_y)
print('Predicted author:', clf.predict([example_X])[0])
Actual author: AaronPressman Predicted author: AaronPressman
from sklearn.svm import SVC
Define pipeline
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
train_and_evaluate(clf_svm, X_train, X_test, y_train, y_test)
Accuracy on training set: 0.9975 Accuracy on testing set: 0.83 Classification Report: precision recall f1-score support AaronPressman 0.89 0.89 0.89 9 AlanCrosby 0.79 0.92 0.85 12 AlexanderSmith 1.00 0.70 0.82 10 BenjaminKangLim 0.67 0.36 0.47 11 BernardHickey 1.00 0.50 0.67 10 BradDorfman 0.78 0.88 0.82 8 DarrenSchuettler 0.89 0.89 0.89 9 DavidLawder 1.00 0.60 0.75 10 EdnaFernandes 0.73 0.89 0.80 9 EricAuchard 0.73 0.89 0.80 9 FumikoFujisaki 1.00 1.00 1.00 10 GrahamEarnshaw 0.83 1.00 0.91 10 HeatherScoffield 0.80 0.89 0.84 9 JanLopatka 0.67 0.44 0.53 9 JaneMacartney 0.36 0.50 0.42 10 JimGilchrist 0.88 0.88 0.88 8 JoWinterbottom 1.00 0.90 0.95 10 JoeOrtiz 0.82 1.00 0.90 9 JohnMastrini 0.83 0.88 0.86 17 JonathanBirt 0.80 1.00 0.89 8 KarlPenhaul 0.93 1.00 0.96 13 KeithWeir 0.83 1.00 0.91 10 KevinDrawbaugh 0.82 0.90 0.86 10 KevinMorrison 0.50 1.00 0.67 3 KirstinRidley 1.00 0.56 0.71 9 KouroshKarimkhany 0.88 0.88 0.88 8 LydiaZajc 1.00 1.00 1.00 10 LynneO'Donnell 0.82 0.82 0.82 11 LynnleyBrowning 1.00 1.00 1.00 13 MarcelMichelson 1.00 0.67 0.80 12 MarkBendeich 0.79 1.00 0.88 11 MartinWolk 0.83 1.00 0.91 5 MatthewBunce 1.00 0.86 0.92 14 MichaelConnor 1.00 0.85 0.92 13 MureDickie 0.60 0.60 0.60 10 NickLouth 0.90 0.90 0.90 10 PatriciaCommins 1.00 1.00 1.00 9 PeterHumphrey 0.57 0.89 0.70 9 PierreTran 0.60 1.00 0.75 6 RobinSidel 1.00 1.00 1.00 12 RogerFillion 1.00 1.00 1.00 8 SamuelPerry 0.81 0.93 0.87 14 SarahDavison 1.00 0.71 0.83 14 ScottHillis 0.67 0.44 0.53 9 SimonCowell 1.00 0.90 0.95 10 TanEeLyn 0.83 0.71 0.77 7 TheresePoletti 0.91 0.91 0.91 11 TimFarrand 0.92 0.85 0.88 13 ToddNissen 0.90 1.00 0.95 9 WilliamKazer 0.27 0.30 0.29 10 accuracy 0.83 500 macro avg 0.84 0.83 0.82 500 weighted avg 0.85 0.83 0.83 500
Save results
joblib.dump(clf_svm, 'svm_results.pkl')
['svm_results.pkl']
Predict out of sample:
example_y, example_X = y_train[33], X_train[33]
print('Actual author:', example_y)
print('Predicted author:', clf_svm.predict([example_X])[0])
Actual author: AaronPressman Predicted author: AaronPressman
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.
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:
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:
grid = GridSearchCV(clf_search,
param_grid=parameters,
scoring=make_scorer(f1_score, average='micro'),
n_jobs=-1
)
grid.fit(X_train, y_train)
GridSearchCV(estimator=Pipeline(steps=[('vect', TfidfVectorizer()), ('clf', SVC())]), n_jobs=-1, param_grid={'clf__C': [8, 10, 12], 'clf__gamma': [0.2, 0.3, 0.4], 'clf__kernel': ['rbf'], 'vect__max_features': [1500], 'vect__ngram_range': [(1, 1), (2, 2)], 'vect__stop_words': ['english'], 'vect__strip_accents': ['unicode']}, scoring=make_scorer(f1_score, average=micro))
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
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))
The best parameters are {'clf__C': 8, 'clf__gamma': 0.4, 'clf__kernel': 'rbf', 'vect__max_features': 1500, 'vect__ngram_range': (1, 1), 'vect__stop_words': 'english', 'vect__strip_accents': 'unicode'} with a score of 0.79 precision recall f1-score support AaronPressman 0.89 0.89 0.89 9 AlanCrosby 0.79 0.92 0.85 12 AlexanderSmith 1.00 0.70 0.82 10 BenjaminKangLim 0.67 0.36 0.47 11 BernardHickey 1.00 0.50 0.67 10 BradDorfman 0.78 0.88 0.82 8 DarrenSchuettler 1.00 0.89 0.94 9 DavidLawder 1.00 0.60 0.75 10 EdnaFernandes 0.73 0.89 0.80 9 EricAuchard 0.73 0.89 0.80 9 FumikoFujisaki 1.00 1.00 1.00 10 GrahamEarnshaw 0.83 1.00 0.91 10 HeatherScoffield 0.82 1.00 0.90 9 JanLopatka 0.60 0.33 0.43 9 JaneMacartney 0.36 0.50 0.42 10 JimGilchrist 0.88 0.88 0.88 8 JoWinterbottom 1.00 0.90 0.95 10 JoeOrtiz 0.82 1.00 0.90 9 JohnMastrini 0.79 0.88 0.83 17 JonathanBirt 0.80 1.00 0.89 8 KarlPenhaul 0.93 1.00 0.96 13 KeithWeir 0.83 1.00 0.91 10 KevinDrawbaugh 0.82 0.90 0.86 10 KevinMorrison 0.60 1.00 0.75 3 KirstinRidley 1.00 0.56 0.71 9 KouroshKarimkhany 0.88 0.88 0.88 8 LydiaZajc 1.00 1.00 1.00 10 LynneO'Donnell 0.82 0.82 0.82 11 LynnleyBrowning 1.00 1.00 1.00 13 MarcelMichelson 1.00 0.67 0.80 12 MarkBendeich 0.73 1.00 0.85 11 MartinWolk 0.83 1.00 0.91 5 MatthewBunce 1.00 0.86 0.92 14 MichaelConnor 1.00 0.85 0.92 13 MureDickie 0.60 0.60 0.60 10 NickLouth 0.90 0.90 0.90 10 PatriciaCommins 1.00 1.00 1.00 9 PeterHumphrey 0.57 0.89 0.70 9 PierreTran 0.60 1.00 0.75 6 RobinSidel 1.00 1.00 1.00 12 RogerFillion 1.00 1.00 1.00 8 SamuelPerry 0.76 0.93 0.84 14 SarahDavison 1.00 0.71 0.83 14 ScottHillis 0.67 0.44 0.53 9 SimonCowell 1.00 0.90 0.95 10 TanEeLyn 0.83 0.71 0.77 7 TheresePoletti 0.90 0.82 0.86 11 TimFarrand 0.92 0.85 0.88 13 ToddNissen 0.90 1.00 0.95 9 WilliamKazer 0.27 0.30 0.29 10 accuracy 0.83 500 macro avg 0.84 0.83 0.82 500 weighted avg 0.85 0.83 0.82 500
from sklearn.decomposition import LatentDirichletAllocation
Vectorizer (using countvectorizer for the sake of example)
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
n_topics = 10
n_top_words = 25
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
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
result_df = save_top_words(lda, vectorizer.get_feature_names(), n_top_words)
result_df
topic_id | top_words | |
---|---|---|
0 | 1 | company pound million share group business bil... |
1 | 2 | official south people north northern police ko... |
2 | 3 | china kong hong beijing chinese deng year part... |
3 | 4 | market percent price year china trade bank sta... |
4 | 5 | percent year million profit analyst quarter sh... |
5 | 6 | gold bre canada toronto stock busang canadian ... |
6 | 7 | ford union oil strike car plant new worker pro... |
7 | 8 | tonne year million crop new world export add a... |
8 | 9 | company service new network computer internet ... |
9 | 10 | bank financial fund nomura company loan firm s... |
%matplotlib inline
import pyLDAvis
import pyLDAvis.sklearn
pyLDAvis.enable_notebook()
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
Interested? Check out the Stanford course CS224n (Page)!