Last issue article :「12」 You guys ,naive!—— Simple Bayes talks in , We analyze the essence and characteristics of naive Bayesian algorithm and some knowledge of Bayesian school . Here we use python code Naive Bayes The realization of computation . The first 1 In part, novel coronavirus pneumonia is calculated for sneezing workers. , The first 2 Some of them are watermelon classification projects mentioned in the previous article .
class NBClassify(object):
def __init__(self, fillNa = 1):
self.fillNa = 1
pass
def train(self, trainSet):
# Calculate the probability of each category
# Save all tag All kinds of , And their frequency
dictTag = {}
for subTuple in trainSet:
dictTag[str(subTuple[1])] = 1
if
str(subTuple[1]) not in dictTag.keys()
else
dictTag[str(subTuple[1])] + 1
# Save every tag Its own probability
tagProbablity = {}
totalFreq = sum([value for value in dictTag.values()])
for key, value in dictTag.items():
tagProbablity[key] = value / totalFreq
# print(tagProbablity)
self.tagProbablity = tagProbablity
###########