以下Python朴素贝叶斯代码需要一些建议。我的csv(NB.csv)不断出现“ ZeroDivisionError:浮点除以零”错误,但另一个csv(data.csv)则运行良好... 我正在运行python 3.6(也尝试过2.7)。
# Example of Naive Bayes implemented from Scratch in Python
import csv
import random
import math
def loadCsv(filename):
lines = csv.reader(open(filename, "r"))
dataset = list(lines)
for i in range(len(dataset)):
dataset[i] = [float(x) for x in dataset[i]]
return dataset
def splitDataset(dataset, splitRatio):
trainSize = int(len(dataset) * splitRatio)
trainSet = []
copy = list(dataset)
while len(trainSet) < trainSize:
index = random.randrange(len(copy))
trainSet.append(copy.pop(index))
return [trainSet, copy]
def separateByClass(dataset):
separated = {}
for i in range(len(dataset)):
vector = dataset[i]
if (vector[-1] not in separated):
separated[vector[-1]] = []
separated[vector[-1]].append(vector)
return separated
def mean(numbers):
return sum(numbers) / float(len(numbers))
def stdev(numbers):
avg = mean(numbers)
variance = sum([pow(x - avg, 2) for x in numbers]) / float(len(numbers) - 1)
return math.sqrt(variance)
def summarize(dataset):
summaries = [(mean(attribute), stdev(attribute)) for attribute in zip(*dataset)]
del summaries[-1]
return summaries
def summarizeByClass(dataset):
separated = separateByClass(dataset)
summaries = {}
for classValue, instances in separated.items():
summaries[classValue] = summarize(instances)
return summaries
def calculateProbability(x, mean, stdev):
exponent = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev, 2))))
print (stdev,"||",exponent)
print (2 * math.pow(stdev, 2))
return (1 / (math.sqrt(2 * math.pi) * stdev)) * exponent
def calculateClassProbabilities(summaries, inputVector):
probabilities = {}
for classValue, classSummaries in summaries.items():
probabilities[classValue] = 1
for i in range(len(classSummaries)):
mean, stdev = classSummaries[i]
x = inputVector[i]
print ("x: ",x,"mean: ", mean,"stdev: ", stdev," || ","summaries: " ,summaries,"inputVector: ",inputVector,"i:",[i])
probabilities[classValue] *= calculateProbability(x, mean, stdev)
return probabilities
def predict(summaries, inputVector):
probabilities = calculateClassProbabilities(summaries, inputVector)
bestLabel, bestProb = None, -1
for classValue, probability in probabilities.items():
if bestLabel is None or probability > bestProb:
bestProb = probability
bestLabel = classValue
return bestLabel
def getPredictions(summaries, testSet):
predictions = []
for i in range(len(testSet)):
result = predict(summaries, testSet[i])
predictions.append(result)
return predictions
def getAccuracy(testSet, predictions):
correct = 0
for i in range(len(testSet)):
if testSet[i][-1] == predictions[i]:
correct += 1
return (correct / float(len(testSet))) * 100.0
def main():
filename = 'C:\\Users\\common\\Dropbox\\Project\\NB.csv'
splitRatio = 0.67
dataset = loadCsv(filename)
print ("Load csv")
trainingSet, testSet = splitDataset(dataset, splitRatio)
print('Split ' + str(len(dataset)) + ' rows into train=' + str(len(trainingSet)) + ' and test= '+ str(len(testSet)) +' rows')
# prepare model
summaries = summarizeByClass(trainingSet)
predictions = getPredictions(summaries, testSet)
accuracy = getAccuracy(testSet, predictions)
print('Accuracy: ' + str(accuracy))
main()
但是代码不断提示此错误”
回溯(最近通话最近):文件 “ C:/Users/common/PycharmProjects/Lab/NB_raw.py”,第123行,在 main()main中的文件“ C:/Users/common/PycharmProjects/Lab/NB_raw.py”,第117行 预测= getPredictions(摘要,测试集)文件“ C:/Users/common/PycharmProjects/Lab/NB_raw.py”,第92行,在 getPredictions 结果=预测(预测,testSet [i])文件“ C:/Users/common/PycharmProjects/Lab/NB_raw.py”,预测中的第79行 概率=计算类概率(摘要,inputVector)文件“ C:/Users/common/PycharmProjects/Lab/NB_raw.py”, 第74行,在calculateClassProbabilities中 probabilities [classValue] * = calculateProbability(x,平均值,stdev)文件“ C:/Users/common/PycharmProjects/Lab/NB_raw.py”,第60行,在 计算概率 exponent = math.exp(-(math.pow(x-mean,2)/(2 * math.pow(stdev,2))))ZeroDivisionError:浮点除以零“
答案 0 :(得分:0)
您的代码中有一个def calculateProbability
,应该是:
def calculateProbability(x, mean, stdev):
try:
exponent = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev, 2))))
except ZeroDivisionError:
exponent = 0 #or whatever
print (stdev,"||",exponent)
print (2 * math.pow(stdev, 2))
return (1 / (math.sqrt(2 * math.pi) * stdev)) * exponent
答案 1 :(得分:0)
之所以这样做,是因为您试图在calculateProbability
函数中将其除以0。
因此,您可以在try-catch语句中进行检查。尝试将calculateProbability
函数编辑到下面,然后查看它是否运行:
def calculateProbability(x, mean, stdev):
exponent = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev, 2))))
print (stdev,"||",exponent)
print (2 * math.pow(stdev, 2))
try:
return (1 / (math.sqrt(2 * math.pi) * stdev)) * exponent
except ZeroDivisionError:
return 0