Search code examples
rmachine-learningnaivebayes

Printing conditional probabilities from Naive Bayes Model in R


I have created a model using e1071 package for Naive Bayes classifier. I need to print the conditional probabilities in below format.

P(C=c1)=0.32 P(A1=x1|c1)=0.33 P(A1=x2|c1)=0.67 P(A2=y1|c1)=0.25 P(A2=y2|c1)=0.75 P(A3=z1|c1)=0.26 P(A3=z2|c1)=0.49 P(A3=z3|c1)=0.25

When I type model name, I can see the conditional probabilities but don't know how to access individual value and use it to print result in above format.

I am new to R and not sure how to parse model and get data in this form. How to parse model and separate out data?


Solution

  • Just print $tables

    > data(Titanic)
    > m <- naiveBayes(Survived ~ ., data = Titanic)  
    > m$tables
    $Class
            Class
    Survived        1st        2nd        3rd       Crew
         No  0.08187919 0.11208054 0.35436242 0.45167785
         Yes 0.28551336 0.16596343 0.25035162 0.29817159
    
    $Sex
            Sex
    Survived       Male     Female
         No  0.91543624 0.08456376
         Yes 0.51617440 0.48382560
    
    $Age
            Age
    Survived      Child      Adult
         No  0.03489933 0.96510067
         Yes 0.08016878 0.91983122
    

    And now you can read out for example P(Age=Child|Survived=No) = 3% and P(Age=Child|Survived=yes) = 8%, P(Class=Crew|Survived=No) = 45% and so on.