Text classification using Naive Bayes (R)

This is my first modest article about the Bayes method using R language, I aim from this article distribute the principle of statistics in the Arabic community, so I will using two language Arabic and English, to be useful for my Arabic friends and foreign friends.

so I hope find the the article fast and easy and if you have any question or need any clarification don’t hesitant to sent to my email :

I will focus on the practical part only, how apply the Bayes method in our live to be more useful for us.

start from call the library that we need

تصنيف النصوص باستخدام خوارزمية بايز

هذه هي أول مقالة متواضعة عن طريقة بايز باستخدام لغة R ، أهدف من هذه المقالة إلى نشر مبادئ الإحصاء في المجتمع العربي ، لذلك سأستخدم الغتين العربية والإنجليزية ،لتكون مفيدة لأصدقائي العرب وأصدقائي الأجانب.

لذلك أتمنى أن تجدوا المقال سريعًا وسهلاً وإذا كان لديكم أي سؤال أو بحاجة إلى أي توضيح فلا تترددوا في إرساله إلى بريدي الإلكتروني Obada.aladeeb@gmail.com

سأركز على الجزء العملي فقط ، كيف نطبق طريقة بايز في حياتنا لنكون أكثر فائدة لنا.

نبدأ من الاتصال بالمكتبة التي نحتاجها

library(tm)
## Loading required package: NLP
library(tidyr)
library("dplyr")
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union

In the first we will apply the Bayes method to classification the email between spam and ham

Now lets get data from the link (https://drive.google.com/file/d/0B8jkcc4fRf35c3lRRC1LM3RkV0k/view)

and get data into R

في البداية سنطبق طريقة Bayes لتصنيف البريد الإلكتروني بين البريد العشوائي و عادي أو ham

دعونا نحصل على البيانات من الرابط التالي : 

https://drive.google.com/file/d/0B8jkcc4fRf35c3lRRC1LM3RkV0k/view

وندخل البيانات إلى لغة R من  خلال الكود التالي

library(readr)
sms_spam <- read.csv("D:/Files/Jamaa/Learn R Jamaa/sms_spam.csv")

change the text data to Corpus

using this code from tm library, we will change the data to be Corpus

تغيير البيانات النصية إلى مجموعة

باستخدام هذا الرمز من مكتبة tm ، سنقوم بتغيير البيانات لتكون Corpus

 

sms <- Corpus((VectorSource(sms_spam$text)))
and see the result

ولمشاهدة النتيجة ننفذ الأمر 

inspect(sms[1:5])
## <<SimpleCorpus>>
## Metadata:  corpus specific: 1, document level (indexed): 0
## Content:  documents: 5
## 
## [1] Hope you are having a good week. Just checking in                                                                                                                
## [2] K..give back my thanks.                                                                                                                                          
## [3] Am also doing in cbe only. But have to pay.                                                                                                                      
## [4] complimentary 4 STAR Ibiza Holiday or £10,000 cash needs your URGENT collection. 09066364349 NOW from Landline not to lose out! Box434SK38WP150PPM18+           
## [5] okmail: Dear Dave this is your final notice to collect your 4* Tenerife Holiday or #5000 CASH award! Call 09061743806 from landline. TCs SAE Box326 CW25WX 150ppm

Cleaning data

Now we will cleaning data using tm library to remove the Numbers,Punctuation,stop words and change all character to be lower , that is through below code

تنظيف البيانات

سنقوم الآن بتنظيف البيانات باستخدام مكتبة tm لإزالة الأرقام وعلامات الترقيم وكلمات الوصل وتغيير كل الأحرف لتكون صغيرة ، وذلك من خلال الكود أدناه

sms_clean<- tm_map(sms , tolower)
## Warning in tm_map.SimpleCorpus(sms, tolower): transformation drops documents
sms_clean<-tm_map(sms_clean,removeNumbers)
## Warning in tm_map.SimpleCorpus(sms_clean, removeNumbers): transformation drops
## documents
sms_clean<-tm_map(sms_clean,removePunctuation)
## Warning in tm_map.SimpleCorpus(sms_clean, removePunctuation): transformation
## drops documents
sms_clean<-tm_map(sms_clean,removeWords, stopwords("en"))
## Warning in tm_map.SimpleCorpus(sms_clean, removeWords, stopwords("en")):
## transformation drops documents
sms_clean<-tm_map(sms_clean,stripWhitespace)
## Warning in tm_map.SimpleCorpus(sms_clean, stripWhitespace): transformation drops
## documents

Now we can show the find the result of text data

الأن يمكننا أن نشاهد نتيجة التي وصلت لها البيانات النصية

inspect(sms_clean[1:5])
## <<SimpleCorpus>>
## Metadata:  corpus specific: 1, document level (indexed): 0
## Content:  documents: 5
## 
## [1] hope good week just checking                                                                        
## [2] kgive back thanks                                                                                   
## [3]  also cbe pay                                                                                       
## [4] complimentary star ibiza holiday ⣠cash needs urgent collection now landline lose boxskwpppm       
## [5] okmail dear dave final notice collect tenerife holiday cash award call landline tcs sae box cwwx ppm

Create Document Term Matrix

Now we will create the Create Document Term Matrix DTM , this Matrix mean I will add each word in the column and then see frequency of each word in each sms (row), I will do that using below Code

إن شاء مصفوفة الكلمات DTM

سنقوم الآن بإنشاء مصفوفة الكلمات DTM ، وتعني هذه المصفوفة أنني سأضيف كل كلمة في العمود ثم أرى تكرار كل كلمة في كل رسالة قصيرة (صف)، وسأفعل ذلك باستخدام الكود أدناه

dtm <- DocumentTermMatrix(sms_clean)

To see the result

لمشاهدة نتيجة المصفوفة من خلال الأمر

inspect(dtm[1:10,10:15])
## <<DocumentTermMatrix (documents: 10, terms: 6)>>
## Non-/sparse entries: 7/53
## Sparsity           : 88%
## Maximal term length: 13
## Weighting          : term frequency (tf)
## Sample             :
##     Terms
## Docs boxskwpppm cash cbe collection complimentary pay
##   1           0    0   0          0             0   0
##   10          0    0   0          0             0   0
##   2           0    0   0          0             0   0
##   3           0    0   1          0             0   1
##   4           1    1   0          1             1   0
##   5           0    1   0          0             0   0
##   6           0    0   0          0             0   0
##   7           0    0   0          0             0   0
##   8           0    0   0          0             0   0
##   9           0    0   0          0             0   0

prepare training and test data

index of test and training data using sampling way

Now we will start sampling to get the index for training and test data, in the end i will get random sample for training and testing data

that using the below Code

تجهيز بيانات التدريب وبيانات الإختبار:

تحديد مؤشر بيانات التدريب و بيانات الإختبار من خلال أخذ عينة من البيانات

سنبدأ الآن في أخذ العينات للحصول على مؤشر بيانات التدريب والاختبار ، وفي النهاية سأحصل على عينة عشوائية لبيانات التدريب والاختبار

 

training.index<-sample(1:nrow(sms_spam),nrow(sms_spam)*0.7,replace = FALSE)
test.index <- as.integer(rownames(sms_spam[-training.index,]))

prepare training and test label

Here in this part i will create the the label(spam and ham) of training and test data

تجهيز وصف بيانات التدريب وبيانات الإختبار

في هذا الجزء سأقوم بوصف كل سطر من البيانات التدريب وبيانات الإختبار هل هي spam أو هي ham 

sms_training_label<-sms_spam[training.index,]$type
sms_test_label<-sms_spam[test.index,]$type

Mow from the privies step I will see the property for each label

for training data

من الخطوة السابقة سأقوم بعرض إحتمال كل وصف من spam  و ham  في بيانات التدريب وبيانات الإختبار

لبيانات التدريب  

 prop.table(table( sms_spam$type[training.index]))
## 
##       ham      spam 
## 0.8640452 0.1359548
For testing data

لبيانات الإختبار 

prop.table(table( sms_spam$type[test.index]))
## 
##       ham      spam 
## 0.8693046 0.1306954

DTM traning and test matrix

Here I will separate the DTM to training and test to be two matrix training and test matrix depend on the training and test index

مجموعات التدريب والإختبار في مصفوفة الكلمات DTM

سنقوم بفصل كل من مصفوفة الكلمات لمصفوفتين مصفوفة الكلمات للتدريب ومصفوفة الكلمات للإختبار بالإعتماد على مؤشر التدريب والإختبار الذي تم إعداداه سابقا

dtm_training <- dtm[training.index,]
dtm_test <-dtm[test.index,]

create yes_no function

I will create yes no function to change all number in the DTM to be Yes or No if the cell is 0 give me “no” if the cell more than 0 give me “yes”

I will create the function in the below code

إعداد دالة نعم لا 

سأقوم بإعداد دالة تقوم بتغير كل القيم الرقيمة في مصفوفة الكلمات إلى أن تكون نعم أو لا (yes , no ) كل خلية قيمتها  تأخذ القيمة no وكل خليه قيمتها أكبر من الصفر تأخذ القيمة yes وذلك من خلال الكود التالي

yes_or_no <- function(x){
  
  y<- if_else(x>0 , 1 , 0)
  y<- factor(y,levels = c(0,1), labels = c("no","yes"))
  y
}

Then i will apply it on the training and test matrix (DTM)

ثم سأقوم بتطبيق الدالة على كل من مصفوفة الكلمات التدريبية والإختبار 

sms_training <- apply(dtm_training,2, yes_or_no )
sms_test<- apply(dtm_test, 2, yes_or_no)
Now the data is ready to apply Naive Bayes algorithm

الأن البيانات جاهزة لنطبق خوازرمية بايز (خوارزمية ذكاء صناعي)

Naive Bayes model

First get the library(e1071)

نحمل المكنبة e1071

library(e1071)

Now add the training matrix which we changed it to be yes no matrix and the label training data in the naive Bayes algorithm function to training the algorithm to be ready to test step as below code

أضف الآن مصفوفة التدريب التي قمنا بتغييرها سابقا إلى نعم لا  وتصنيف بيانات تدريب التي قمنا به سابقا في دالة خوارزمية Bayes وذلك لتدريب الخوارزمية لتكون جاهزة لخطوة الإختبار كما هو موضح أدناه

Naiv_sms_classifier<- naiveBayes (sms_training, sms_training_label)

after 5 min more or less , we will have Naive Bayes model under Naiv_sms_classifier

Now let’s us using this model to prediction the test data, that is through using test matrix(DTM) which we changed it to be yes no matrix

بعد خمس دقائق أكثر أو قل , نحصل على نموذج بايز تحت اسم المتغير  Naiv_sms_classifier 

دعونا الأن نقوم بالتنبوء بقيمة بيانات الإختبار وذلك من خلال استخدام مصفوفة الكلمات التي تم تغيرها لتكون مصفوفة yes no  و

sms_prediction<- predict( Naiv_sms_classifier ,newdata = sms_test)  

Now let’s us know the accuracy of prediction that through create the comparison table between prediction and actual data

الآن دعنا نعرف دقة التنبؤ من خلال إنشاء جدول المقارنة بين التنبؤ والبيانات الفعلية

table(sms_prediction,sms_test_label)
##               sms_test_label
## sms_prediction  ham spam
##           ham  1442   23
##           spam    8  195

From the table we can see 1430 emails were ham in actual and in the prediction also ham and 197 emails were spam in actual and the prediction also from this table i can calculate the accuracy which is the (ham ham + spam spam)/ (total)

or i can using the below code

من الجدول يمكننا أن نرى 1430 بريدًا إلكترونيًا كانت عادية في الواقع وفي التنبؤ أيضًا كذلك  و 197 بريدًا إلكترونيًا كانت بريدًا عشوائيًا في الواقع والتنبؤ بها أيضًا من هذا الجدول يمكنني حساب الدقة 

(ham ham + spam spam)/ (total)

sum(table(sms_prediction,sms_test_label)[1,1]+table(sms_prediction,sms_test_label)[2,2])/sum(table(sms_prediction,sms_test_label))
## [1] 0.9814149
As we see the accuracy is 0.97 :)

كما نرى الدقة هي 0.97 :)

In the end this is one of the applications of Bayes theory There are many situations and problems in our daily life that need to be classified and Bayes’ theory may be one of the ways for that

في النهاية هذا أحد تطبيقات نظرية بايز
هناك العديد من المواقف والمشكلات في حياتنا اليومية التي تحتاج إلى التصنيف وقد تكون نظرية بايز إحدى الطرق لذلك

By : Obada Aladib

كتبه عبادة