text mining (nlp) with python¶
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
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:
- Identify a data source
- Gather the data
- Process the data
- Analyze the data
This notebook only discusses step 3 and 4. If you want to learn more about step 2 see myPython tutorial.
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
Elements / topics that are discussed in this notebook:¶

Table of Contents¶
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:
SpacyNLTKand the higher-level wrapperTextBlob
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:
pyLDAvisfor visualizing LDA)langdetectfor detecting languagesfuzzywuzzyfor fuzzy text matchingGensimfor topic modelling
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 myPython tutorial (although thezipfile andio operations are not very relevant).
importrequests,zipfile,io,osfromtqdm.notebookimporttqdm
Note: fortqdm 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 *
ifnotos.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':{}}
forlabel,folderintqdm(folder_dict.items()):authors=os.listdir(folder)forauthorinauthors:text_files=os.listdir(os.path.join(folder,author))forfileintext_files:withopen(os.path.join(folder,author,file),'r')astext_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'
Convert the text into a NLP representation¶
We can use the text directly, but if want to use packages likespacy andtextblob 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 Englishnlp = English()OR
import en_core_web_smnlp = en_core_web_sm.load()import en_core_web_mdnlp = en_core_web_md.load()import en_core_web_lgnlp = en_core_web_lg.load()importspacyimporten_core_web_mdnlp=en_core_web_md.load()
Convert all text in the "test" sample to aspacydoc object usingnlp.pipe():
spacy_text={}forauthor,text_listintqdm(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
NLTK¶
importnltk
We can apply basicnltk operations directly to the text so we don't need to convert first.
TextBlob¶
fromtextblobimportTextBlob
Convert all text in the "test" sample to aTextBlob object usingTextBlob():
textblob_text={}forauthor,text_listintext_dict['test'].items():textblob_text[author]=[TextBlob(text)fortextintext_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 usingprint 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 useunidecode
importunidecode
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 bySpacy:
example_paragraph=spacy_text['TimFarrand'][0]
sentence_list=[sforsinexample_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 aspacy 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={}forauthor,text_listintqdm(spacy_text.items()):spacy_sentences[author]=[list(text.sents)fortextintext_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 atoken in this context (hencetokenization), usingspacy:
token_list=[tokenfortokeninexample_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 wordcar.
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_fortokeninexample_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
fromnltk.stem.porterimportPorterStemmerstemmer=PorterStemmer()
stemmed=[stemmer.stem(token.text)fortokeninexample_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)fororiginal,lemma,steminzip(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.
UsingSpacy:
pos_list=[(token,token.pos_)fortokeninexample_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 calledn-grams.
Ann-gram is nothing more than a a combination ofN 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
UsingNLTK:
bigram_list=['-'.join(x)forxinnltk.bigrams([token.textfortokeninexample_sentence])]bigram_list[10:15]
['are-likely', 'likely-to', 'to-be', 'be-held', 'held-back']
Usingspacy
deftokenize_without_punctuation(sen_obj):return[token.textfortokeninsen_objiftoken.is_alpha]
defcreate_ngram(sen_obj,n,sep='-'):token_list=tokenize_without_punctuation(sen_obj)number_of_tokens=len(token_list)ngram_list=[]fori,tokeninenumerate(token_list[:-n+1]):ngram_item=[token_list[i+ii]foriiinrange(n)]ngram_list.append(sep.join(ngram_item))returnngram_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.
UsingSpacy:
no_stop_words=[tokenfortokeninexample_sentenceifnottoken.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:
[tokenfortokeninexample_sentenceifnottoken.is_stopandtoken.is_alpha][:10]
[Shares, brewing, leisure, group, Bass, Plc, likely, held, Britain, Trade]
Wrap everything into one function¶
Basic SpaCy text processing function
- Split into sentences
- Apply lemmatizer, remove top words, remove punctuation
- Clean up the sentence using
textacy
defprocess_text_custom(text):sentences=list(nlp(text,disable=['tagger','ner','entity_linker','textcat','entitry_ruler']).sents)lemmatized_sentences=[]forsentenceinsentences:lemmatized_sentences.append([token.lemma_fortokeninsentenceifnottoken.is_stopandtoken.is_alpha])return[' '.join(sentence)forsentenceinlemmatized_sentences]
spacy_text_clean={}forauthor,text_listintqdm(text_dict['test'].items()):lst=[]fortextintext_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=0forauthor,textsinspacy_text_clean.items():fortextintexts: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 usespacy_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_)foriinnlp(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_)foriinnlp(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-inre (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
importre
TIP: UsePythex.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-AZ663-BY
Example 2:¶
If a sentence contains the word 'million' return True, otherwise return False
forseninspacy_text_clean['TimFarrand'][2]:TERM='million'ifre.search('million',sen,flags=re.IGNORECASE):print(sen)
Analysts forecast pretax profit range million stg restructure cost million timerestructure cost million anticipate bulk million stem closure small production plant FranceCadbury drink business turn million stg trade profit million half entirely contribution Dr PepperCampbell estimate UK beverage contribute million stg operate profit million timeBroadly analyst expect pretty flat performance group confectionery business consensus forecast million stg operate profitaverage analyst calculate beverage chip trade profit millionsale percent stake Coca Cola amp Schweppes Beverages CCSB operation Coca Cola Enterprises June million stg analyst want clear statement strategy companyfar analyst company say shareholder expect return investment emerge market large far million Russian plantCadbury announce investment million stg build new plant Wrocoaw Poland joint venture China cost millionNet 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([xforxinspacy_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 thespacy-langdetect package it is easy to detect the language of a piece of text
fromspacy_langdetectimportLanguageDetectornlp.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 asspacy_readability
fromspacy_readabilityimportReadability
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.4128571428571450
Manual example: FOG index
importsyllapy
defcalculate_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=0num_complex_words=0forsen_objinsen_list:words_in_sen=[token.textfortokeninsen_objiftoken.is_alpha]num_words+=len(words_in_sen)num_complex=0forwordinwords_in_sen:num_syl=syllapy.count(word.lower())ifnum_syl>2:num_complex+=1num_complex_words+=num_complexfog=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}Text similarity¶
Usingfuzzywuzzy¶
fromfuzzywuzzyimportfuzz
fuzz.ratio("fuzzy wuzzy was a bear","wuzzy fuzzy was a bear")
91
Usingspacy¶
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.
Example 1:¶
word_dictionary=['soft','first','most','be']
forwordinword_dictionary:print(word,example_paragraph.count(word))
soft 2first 0most 0be 7
Example 2:¶
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=0forwordinpos:pos_count+=sentence.lower().count(word)print(pos_count)neg_count=0forwordinneg:neg_count+=sentence.lower().count(word)print(neg_count)pos_count/(neg_count+pos_count)
41
0.8
Getting the total number of words is also easy:
num_tokens=len([tokenfortokeninnlp(sentence)iftoken.is_alpha])num_tokens
19
Example 3:¶
We can also save the count per word
pos_count_dict={}forwordinpos: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 theCountVectorizer andTfidfVectorizer 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 websiteclick here
fromsklearn.feature_extraction.textimportCountVectorizerfromsklearn.feature_extraction.textimportTfidfVectorizer
Simple example:¶
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')fordoc_tf_vectorintf.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])
fordoc_vectorintfidf.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. ]
More elaborate example:¶
clean_paragraphs=[]forauthor,valueinspacy_text_clean.items():forarticleinvalue:clean_paragraphs.append(' '.join([xforxinarticle]))
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: 2500Number of words in dictionary: 21978
tfidf_large<2500x21978 sparse matrix of type '<class 'numpy.float64'>'with 410121 stored elements in Compressed Sparse Row format>
Theen_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.")fortokenintokens:iftoken.is_alpha:print(token.text,token.has_vector,token.vector_norm,token.is_oov)
The True 4.70935 FalseDutch True 6.381229 Falseword True 5.8387117 Falsefor True 4.8435082 Falsepeanut True 7.085804 Falsebutter True 7.466713 Falseis True 4.890306 Falsepindakaas False 0.0 Falsedid True 5.284421 Falseyou True 5.1979666 Falseknow True 5.160699 Falsethat True 4.8260193 FalseThis True 5.0461264 Falseis True 4.890306 Falsea True 5.306696 Falsetyppo 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 runnltk.download('brown') to install the NLTK corpus files
importgensimfromnltk.corpusimportbrown
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").
fromsklearn.model_selectionimportcross_val_score,KFold,train_test_splitfromsklearn.pipelineimportPipelinefromsklearn.feature_extraction.textimportTfidfVectorizerfromsklearnimportmetricsimportjoblib
importpandasaspdimportnumpyasnp
Convert the data into a pandas dataframe (so that we can input it easier)¶
article_list=[]forauthor,valueinspacy_text_clean.items():forarticleinvalue:article_list.append((author,' '.join([xforxinarticle])))
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... |
Split the sample into a training and test sample¶
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
Train and evaluate function¶
Simple function to train (i.e. fit) and evaluate the model
deftrain_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))
fromsklearn.naive_bayesimportMultinomialNB
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.8345Accuracy on testing set:0.72Classification 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 9KouroshKarimkhany 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: AaronPressmanPredicted author: AaronPressman
fromsklearn.svmimportSVC
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.9975Accuracy on testing set:0.83Classification 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 9KouroshKarimkhany 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: AaronPressmanPredicted author: AaronPressman
Both theTfidfVectorizer andSVC() estimator take a lot of hyperparameters.
It can be difficult to figure out what the best parameters are.
We can useGridSearchCV to help figure this out.
fromsklearn.model_selectionimportGridSearchCVfromsklearn.metricsimportmake_scorerfromsklearn.metricsimportf1_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 9KouroshKarimkhany 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 500fromsklearn.decompositionimportLatentDirichletAllocation
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=10n_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
defsave_top_words(model,feature_names,n_top_words):out_list=[]fortopic_idx,topicinenumerate(model.components_):out_list.append((topic_idx+1," ".join([feature_names[i]foriintopic.argsort()[:-n_top_words-1:-1]])))out_df=pd.DataFrame(out_list,columns=['topic_id','top_words'])returnout_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 inlineimportpyLDAvisimportpyLDAvis.sklearnpyLDAvis.enable_notebook()
pyLDAvis.sklearn.prepare(lda,tf_large,vectorizer,n_jobs=-1)
Warning: there is a small bug that when you show thepyLDAvis visualization it will hide some of the icons of JupyterLab
Interested? Check out the Stanford course CS224n (Page)!