Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

truncated normal distribution with scipy in python

I am trying to use a truncated normal distribution with scipy in Python3. I want to do something simple: plot the pdf of a truncated normal centered at 0.5 and ranging from 0 to 1. I have the following code line

from scipy import truncnorm
import matplotlib.pyplot as plt
plt.plot([truncnorm.pdf(p,0,1, loc=0.5) for p in np.arange(0,1.1,0.1)])

However, this does not give the nice bell-shaped probability distribution function I would expect. Rather, it equals 0 before 0.5, and I cannot figure out why. Any advice on this?

like image 765
splinter Avatar asked Dec 24 '16 18:12

splinter


People also ask

How do you truncate a distribution?

To truncate a distribution is to restrict its values to an interval and re-normalize the density so that the integral over that range is 1.

What does truncated normal do?

In probability and statistics, the truncated normal distribution is the probability distribution derived from that of a normally distributed random variable by bounding the random variable from either below or above (or both). The truncated normal distribution has wide applications in statistics and econometrics.

How do I import a normal distribution into Python?

We initialize the object of class norm with mean and standard deviation, then using . cdf( ) method passing a value up to which we need to find the cumulative probability value. The cumulative distribution function (CDF) calculates the cumulative probability for a given x-value.

What is scale in Scipy stats norm?

The location ( loc ) keyword specifies the mean. The scale ( scale ) keyword specifies the standard deviation. As an instance of the rv_continuous class, norm object inherits from it a collection of generic methods (see below for the full list), and completes them with details specific for this particular distribution.


1 Answers

Here's the procedure to follow according to the documentation of truncnorm.

# user input
myclip_a = 0
myclip_b = 1
my_mean = 0.5
my_std = 0.3

a, b = (myclip_a - my_mean) / my_std, (myclip_b - my_mean) / my_std
x_range = np.linspace(-1,2,1000)
plt.plot(x_range, truncnorm.pdf(x_range, a, b, loc = my_mean, scale = my_std))

enter image description here

like image 153
Stelios Avatar answered Oct 12 '22 23:10

Stelios