El curso a partir del cual está basada esta pagina se refería a Natural language processing, no Text Analytics. Sin embargo creo que se tratan aspectos que no son sólo de Natural language processing.
Natural language processing (NLP) is concerned with the interactions between computers and human (natural) languages, in particular how to process and analyze large amounts of natural language data. https://en.wikipedia.org/wiki/Natural_language_processing
Challenges in Natural Language Processing frequently involve text classification, speech recognition, natural language understanding, and natural language generation.
Natural Language Processing basically consists of combining machine learning techniques with text, and using math and statistics to get that text in a format that the machine learning algorithms can understand.
The Natural Language Toolkit, or more commonly NLTK, is a suite of libraries and programs for symbolic and statistical natural language processing (NLP) for English written in the Python programming language.
NLTK comes with many corpora, toy grammars, trained models, etc. A complete list is posted at: http://nltk.org/nltk_data/
importnltk# Imports the library
nltk.download()# Download the necessary datasetsThosearesomeoftheimportantdatasetsthatcanbeinstalled:
=>all-corpora
=>all-nltk
After compleated the downloding process as above, the data will be located at $HOME. I have relocated the data to this location:
/home/adelo/.nltk/nltk_data
You will need to set the NLTK_DATA environment variable to specify the location of the data (NOTE: I haven't implement it this way. I actually think I did it and it didn't work but don't rememeber well)
/home/adelo/.bashrc:
What I do is to add the path where I have located the nltk_data to «nltk.data.path». So in the Python script:
nltk.data.path.append('/home/adelo/.nltk/nltk_data')# or to to it generally to every system:
importos
HOME=os.environ['HOME']
nltk.data.path.append(HOME+'/.nltk/nltk_data')
Then, we can test that the data has been installed and the variable properly set as follows (This assumes you downloaded the Brown Corpus):
The SMS Spam Collection v.1 (hereafter the corpus) is a set of SMS tagged messages that have been collected for SMS Spam research. It contains one set of SMS messages in English of 5,574 messages, tagged acording being ham (legitimate) or spam.
The SMS Spam Collection v.1 has a total of 4,827 SMS legitimate messages (86.6%) and a total of 747 (13.4%) spam messages.
The files contain one message per line. Each line is composed by two columns: one with label (ham or spam) and other with the raw text. Here are some examples:
Using these labeled ham and spam examples, we'll train a machine learning model to learn to discriminate between ham/spam automatically. Then, with a trained model, we'll be able to classify arbitrary unlabeled messages as ham or spam.
Let's print the first ten messages and number them using enumerate:
formessage_no,messageinenumerate(messages[:10]):print(message_no,message)print('\n')# Output:0hamGountiljurongpoint,crazy..Availableonlyinbugisngreatworldlaebuffet...Cinetheregotamorewat...1hamOklar...Jokingwifuoni...2spamFreeentryin2awklycomptowinFACupfinaltkts21stMay2005.TextFAto87121toreceiveentryquestion(stdtxtrate)T&C's apply 08452810075over18's3hamUdunsaysoearlyhor...Ucalreadythensay...4hamNahIdon't think he goes to usf, he lives around here though5spamFreeMsgHeytheredarlingit's been 3 week'snowandnowordback!I'd like some fun you up for it still? Tb ok! XxX std chgs to send, £1.50 to rcv6hamEvenmybrotherisnotliketospeakwithme.Theytreatmelikeaidspatent.7hamAsperyourrequest'Melle Melle (Oru Minnaminunginte Nurungu Vettam)'hasbeensetasyourcallertuneforallCallers.Press*9tocopyyourfriendsCallertune8spamWINNER!!Asavaluednetworkcustomeryouhavebeenselectedtoreceivea£900prizereward!Toclaimcall09061701461.ClaimcodeKL341.Valid12hoursonly.9spamHadyourmobile11monthsormore?URentitledtoUpdatetothelatestcolourmobileswithcameraforFree!CallTheMobileUpdateCoFREEon08002986030
Due to the spacing we can tell that this is a TSV ("tab separated values") file, where the first column is a label saying whether the given message is a normal message (commonly known as "ham") or "spam". The second column is the message itself. (Note our numbers aren't part of the file, they are just from the enumerate call).
Instead of parsing TSV manually using Python, we can just take advantage of pandas! Let's go ahead and import it into a DataFrame:
importpandasaspdmessages=pd.read_csv('smsspamcollection/SMSSpamCollection',sep='\t',names=["label","message"])type(messages)# Output:pandas.core.frame.DataFramemessages.head()# output:labelmessage0hamGountiljurongpoint,crazy..Availableonly...1hamOklar...Jokingwifuoni...2spamFreeentryin2awklycomptowinFACupfina...3hamUdunsaysoearlyhor...Ucalreadythensay...4hamNahIdon't think he goes to usf, he lives aro...
From the Histogram, it looks like text length may be a good feature to think about! Let's try to explain why the x-axis of the Histogram goes all the way to 1000ish. This must mean that there is some really long message!
Using describe() over the length we can see that there is a message of 910 characters. This is why the x-axis of the Histogram above goes all the way to 1000ish.
This way we can find the message of 910 characters.
messages[messages['length']==910]['message'].iloc[0]# Output:"For me the love should start with attraction.i should feel that I need her every time around me.she should be the first thing which comes in my thoughts.I would start the day and end it with her.she should be there every time I dream.love will be then when my every breath has her name.my life should happen around her.my life will be named to her.I would cry for her.will give all my happiness and take all her sorrows.I will be ready to fight with anyone for her.I will be in love when I will be doing the craziest things for her.love will be when I don't have to proove anyone that my girl is the most beautiful lady on the whole planet.I will always be singing praises for her.love will be when I start up making chicken curry and end up makiing sambar.life will be the most beautiful then.will get every morning and thank god for the day because she is with me.I would like to say a lot..will tell later.."
Let's focus back on the idea of trying to see if message length is a distinguishing feature between ham and spam.
Very interesting! Through just basic EDA we've been able to discover a trend that spam messages tend to have more characters.
Our main issue with our data is that it is all in text format (strings). The classification algorithms that we've learned about so far will need some sort of numerical feature vector in order to perform the classification task. There are actually many methods to convert a corpus to a vector format. The simplest is the the bag-of-words approach, where each unique word in a text will be represented by one number.
In this section we'll convert the raw messages (sequence of characters) into vectors (sequences of numbers).
As a first step, let's write a function that will split a message into its individual words and return a list. We'll also remove very common words, ('the', 'a', etc..). To do this we will take advantage of the NLTK library. It's pretty much the standard library in Python for processing text and has a lot of useful features. We'll only use some of the basic ones here.
Let's create a function that will process the string in the message column, then we can just use apply() in pandas do process all the text in the DataFrame.
First removing punctuation. We can just take advantage of Python's built-in string library to get a quick list of all the possible punctuation.
Example
Removing punctuation
We can just take advantage of Python's built-in string library to get a quick list of all the possible punctuation: string.punctuation
importstringmess='Sample message! Notice: it has punctuation.'# Check characters to see if they are in punctuationnopunc=[charforcharinmessifcharnotinstring.punctuation]# Join the characters again to form the string.nopunc=''.join(nopunc)print(nopunc)# Output:SamplemessageNoticeithaspunctuation
Remove stopwords
Stopwords are very common words ('the', 'a', etc..).
We can import a list of english stopwords from NLTK (check the documentation for more languages and info).
fromnltk.corpusimportstopwordsstopwords.words('english')[0:10]# Show some stop words# Output:['i','me','my','myself','we','our','ours','ourselves','you','your']nopunc.split()# Output:['Sample','message','Notice','it','has','punctuation']# Now just remove any stopwordsclean_mess=[wordforwordinnopunc.split()ifword.lower()notinstopwords.words('english')]clean_mess# Output:['Sample','message','Notice','punctuation']
Making a function to apply a set of pre-procesteps steps and tokarize the data
Remove Punctuation
Remove Stopwords
Tokenize
We can make a function to to remove Punctuation, Stopwords and Tokenize our messages. This function will be applied to our DataFrame.
Tokenization is just the term used to describe the process of converting the normal text strings in to a list of tokens (words that we actually want).
Notice that this function is returning a list of words without Punctuation or Stopwords.
deftext_process(mess):""" Takes in a string of text, then performs the following: 1. Remove all punctuation 2. Remove all stopwords 3. Returns a list of the cleaned text """# Check characters to see if they are in punctuationnopunc=[charforcharinmessifcharnotinstring.punctuation]# Join the characters again to form the string.nopunc=''.join(nopunc)# Now just remove any stopwordsreturn[wordforwordinnopunc.split()ifword.lower()notinstopwords.words('english')]
Applying the function over our DataFrace
Note: We may get some warnings or errors for symbols we didn't account for or that weren't in Unicode (like a British pound symbol)
# Show original dataframemessages.head()# Output:labelmessagelength0hamGountiljurongpoint,crazy..Availableonly...1111hamOklar...Jokingwifuoni...292spamFreeentryin2awklycomptowinFACupfina...1553hamUdunsaysoearlyhor...Ucalreadythensay...494hamNahIdon't think he goes to usf, he lives aro... 61# Applying the functionmessages['message'].head(5).apply(text_process)# Output0[Go,jurong,point,crazy,Available,bugis,n...1[Ok,lar,Joking,wif,u,oni]2[Free,entry,2,wkly,comp,win,FA,Cup,fin...3[U,dun,say,early,hor,U,c,already,say]4[Nah,dont,think,goes,usf,lives,around,t...
NLTK has lots of built-in tools and great documentation on a lot of these methods. Sometimes they don't work well for text-messages due to the way a lot of people tend to use abbreviations or shorthand, For example:
'Nah dawg, IDK! Wut time u headin to da club?'
Vs.
'No dog, I don't know! What time are you heading to the club?'
Vectorization
Usually, after pre-processing, we have the messages as lists of tokens (also known as lemmas).
Now we'll convert each message, represented as a list of tokens (lemmas) into a Numeric Vector that machine learning models can understand.
To be able to run a Machine Learning algorithm, we first need to transform each text document into a numerical representation in the form of a vector. This matrix will be the numerical representation that a Machine Learning algorithm is able to understand.
We'll do that in three steps using the bag-of-words model:
Create the Document Term Matrix (DTM) (Also know as Term Frequency(TF)): Count how many times does a word occur in each text document.
Term weighting: Weigh the counts, so that frequent tokens get lower weight (Inverse Document Frequency).
Normalization: Normalize the vectors to unit length, to abstract from the original text length (L2 Norm).
Document Term Matrix
We will convert a collection of text documents to a matrix of token counts:
We can imagine a matrix of token counts as a 2-Dimensional matrix. Where the 1-dimension is the entire vocabulary (1 row per word) and the other dimension are the actual documents, in this case a column per text message.
Since there are so many messages, we can expect a lot of zero counts for the presence of that word in that document. Because of this, SciKit-Learn will output a Sparse Matrix.
Each columns (or row depending on the approach) of this matrix represent a word in the training data. Thus, each document is defined by the frequency of the words that are in the dictionary composed for all the terms in our data.
Using Scikit-learn CountVectorizer method to create a DTM
In Python, we can use Scikit-learn's CountVectorizer method to create a DTM. Let's see how to do so in our example:
fromsklearn.feature_extraction.textimportCountVectorizer# This create a «Bag-of-Words (bow) transformed object» (It is not the resulting DTM yet)# There are a lot of arguments and parameters that can be passed to the CountVectorizer. In this case we will just specify the analyzer to be our own previously defined function «text_process»:# Might take a while...bow_transformer=CountVectorizer(analyzer=text_process).fit(messages['message'])# Print total number of vocab words:print(len(bow_transformer.vocabulary_))# Output:11425# Let's take one text message and get its bag-of-words counts as a vector, putting to use our new bow_transformer:message4=messages['message'][3]print(message4)# Output:Udunsaysoearlyhor...Ucalreadythensay...# Now let's see its vector representation:bow4=bow_transformer.transform([message4])print(bow4)print(bow4.shape)# Output:(0,4068)2(0,4629)1(0,5261)1(0,6204)1(0,6222)1(0,7186)1(0,9554)2(1,11425)# This means that there are seven unique words in message number 4 (after removing common stop words). Two of them appear twice, the rest only once.# Let's go ahead and check and confirm which ones appear twice:print(bow_transformer.get_feature_names()[4068])print(bow_transformer.get_feature_names()[9554])# Output:Usay# Now we can use «.transform» on our «Bag-of-Words (bow) transformed object» and transform the entire DataFrame of messages. Let's go ahead and check out how the bag-of-words counts for the entire SMS corpus is a large, sparse matrix:messages_bow=bow_transformer.transform(messages['message'])print('Shape of Sparse Matrix: ',messages_bow.shape)print('Amount of Non-Zero occurences: ',messages_bow.nnz)# Output:ShapeofSparseMatrix:(5572,11444)AmountofNon-Zerooccurences:50795sparsity=(100.0*messages_bow.nnz/(messages_bow.shape[0]*messages_bow.shape[1]))print('sparsity: {}'.format(round(sparsity)))# Output:sparsity:0
Term weighting and Normalization using TF-IDF
In general terms, the process of weighting involves emphasizing the contribution of particular aspects of a phenomenon (or of a set of data) over others to a final outcome or result; thereby highlighting those aspects in comparison to others in the analysis. That is, rather than each variable in the data set contributing equally to the final result, some of the data is adjusted to make a greater contribution than others. https://en.wikipedia.org/wiki/Weighting
TF-IDF, short for Term Frequency–Inverse Document Frequency, and the TF-IDF Weight, is a statistical measure used to evaluate how important a word is to a document in a collection or corpus. It has many uses, most importantly in automated text analysis. It is often used as a weighting factor in machine learning algorithms for Natural Language Processing.
Typically, the TF-IDF Weight is computed by the product of the TF and the IDF
The normalized Term Frequency (TF), which is the number of times a word appears in a document, divided by the total number of words in that document.
Why Normalization?: Since every document is different in length, it is probably that a term would appear much more times in long documents than shorter ones. Thus, the Term Frequency is often divided by the document length (total number of words in that document) as a way of Normalization:
Inverse Document Frequency (IDF). The IDF measures how important a term is. While computing TF, all terms are considered equally important. However it is known that certain terms, such as "is", "of", and "that", may appear a lot of times but have little importance. Thus we need to weigh down the frequent terms while scale up the rare ones, by computing the following:
The IDF is computed as the logarithm of the number of the documents in the corpus divided by the number of documents where the specific term appears.
Example:
Consider a document containing 100 words wherein the word cat appears 3 times.
Then, the normalized Term Frequency for cat is:
Now, assume we have 10 million documents and the word cat appears in one thousand of these.
Then, the Inverse Document Frequency for cat is:
Finally, the TF-IDF Weight is the product of these quantities:
Using TfidfTransformer method from Scikit-learn to compute the TF-IDF
Term weighting and Normalization can be done with TF-IDF, using scikit-learn's TfidfTransformer.
With messages represented as vectors, we can finally train our spam/ham classifier. Now we can actually use almost any sort of classification algorithms. For a variety of reasons, the Naive Bayes classifier algorithm is a good choice.
We can use SciKit-Learn's built-in classification report, which returns precision, recall, f1-score, and a column for support (meaning how many cases supported that classification). Check out the links for more detailed info on each of these metrics and the figure below:
There are quite a few possible metrics for evaluating model performance. Which one is the most important depends on the task and the business effects of decisions based off of the model. For example, the cost of mis-predicting "spam" as "ham" is probably much lower than mis-predicting "ham" as "spam".
In the above "evaluation", we evaluated accuracy on the same data we used for training. You should never actually evaluate on the same dataset you train on!
A proper way is to split the data into a training/test set, where the model only ever sees the training data during its model fitting and parameter tuning. The test data is never used in any way. This is then our final evaluation on test data is representative of true predictive performance.
The test size is 20% of the entire dataset (1115 messages out of total 5572), and the training is the rest (4457 out of 5572). Note the default split would have been 30/70.
Creating a Data Pipeline
Let's run our model again and then predict off the test set. We will use SciKit Learn's pipeline capabilities to store a pipeline of workflow. This will allow us to set up all the transformations that we will do to the data for future use. Let's see an example of how it works:
fromsklearn.pipelineimportPipelinepipeline=Pipeline([('bow',CountVectorizer(analyzer=text_process)),# strings to token integer counts('tfidf',TfidfTransformer()),# integer counts to weighted TF-IDF scores('classifier',MultinomialNB()),# train on TF-IDF vectors w/ Naive Bayes classifier])
Now we can directly pass message text data and the pipeline will do our pre-processing for us! We can treat it as a model/estimator API: