#Calculate the Prob. of class:clsdefP(data,cls_val,cls_name="class"):count=0.0foreindata:ife[cls_name]==cls_val:count+=1returncount/len(data)

# The probability of play or notPY,PN=P(data,"yes"),P(data,"no")PY,PN

(0.6428571428571429, 0.35714285714285715)

#Calculate the Prob(attr|cls)defPT(data,cls_val,attr_name,attr_val,cls_name="class"):count1=0.0count2=0.0foreindata:ife[cls_name]==cls_val:count1+=1ife[attr_name]==attr_val:count2+=1returncount2/count1

# The conditional probability of play or notPT(data,"yes","outlook","sunny"),PT(data,"no","outlook","sunny")

(0.2222222222222222, 0.6)

#Calculate the NBdefNB(data,test,cls_y,cls_n):PY=P(data,cls_y)PN=P(data,cls_n)print'The probability of play or not:',PY,'vs.',PNforkey,valintest.items():PY*=PT(data,cls_y,key,val)PN*=PT(data,cls_n,key,val)printkey,val,'-->play or not:-->',PY,PNreturn{cls_y:PY,cls_n:PN}