user6738499
user6738499

Reputation:

How to fix ZeroDivisionError: float division by zero when calculating Gaussian probability

I'm trying to calculate Gaussian probability, but when I run it through my data I get ZeroDivisionError: float division by zero

here's the code:

def GaussianProbability(x, mean, std):
    exponent = math.exp(-(math.pow(x-mean,2)/(2*math.pow(std,2))))
    return (1 / (math.sqrt(2*math.pi) * std)) * exponent

and the complete error log:

ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-22-b3fd5204c6fa> in <module>
----> 1 precisions_PDZ1,MAP,recalls_PDZ1,fp_rates_PDZ1 = CV_results(PDZ1_graphs,PDZ1_targets,'undirected')

<ipython-input-14-044940745269> in CV_results(list_graphs, list_targets, network_type, multi)
      7     for part in tqdm(range(5)):
      8 
----> 9         probabilities_0,predictions = prediction(list_graphs[part], list_targets[part], network_type, multi)
     10 
     11         if recalls == [] and fp_rates == []:

<ipython-input-12-beeed13223ea> in prediction(graph, actual_edges, network_type, multi)
     11 
     12     for i in tqdm(range(len(X_test))):
---> 13         prob = ClassProbabilities(summaries, prob_class, X_test[i])
     14         if (prob[0]+prob[1])==0:
     15             # both probabilities are too low

<ipython-input-11-286b09a753e9> in ClassProbabilities(summaries, prob_class, x)
      8         for i in range(len(classSummaries)):  # for every attribute
      9             mean, std = classSummaries[i]
---> 10             probabilities[classValue] *= GaussianProbability(x[i], mean, std)
     11 
     12     return probabilities

<ipython-input-10-4a13cc5a69b2> in GaussianProbability(x, mean, std)
      1 def GaussianProbability(x, mean, std):
----> 2     exponent = math.exp(-(math.pow(x-mean,2)/(2*math.pow(std,2))))
      3     return (1 / (math.sqrt(2*math.pi) * std)) * exponent

ZeroDivisionError: float division by zero

Upvotes: 1

Views: 1587

Answers (2)

Hagai Kalinhoff
Hagai Kalinhoff

Reputation: 624

The only place where such error might occur is when (2*math.pow(std,2)) == 0. Which means that for some data your std == 0 this happens when all samples have the exact same value.

You would need to handle such case!

Unless you wish to implement it yourself (not recommended) you can use scipy package:

import scipy
scipy.stats.norm(0, 1).pdf(0)

Visit scipy docs

You can also use the builtin statistics package python offers (better idea for simple and faster calculations). Check it out here

Upvotes: 1

noob
noob

Reputation: 788

your function needs to have an else statement when you standerdv is equal to Zero

you can see this reference it might help What is the normal distribution when standard deviation is zero?

Upvotes: 0

Related Questions