def gen_plot_bernoulli(): # generate bernoulli print("\nBernoulli pmf w/ scipy.stats.bernoulli.pmf(0, p=0.3): {:.3f}". format(bernoulli.pmf(0, p=0.3))) print("\nBernoulli pmf w/ scipy.stats.bernoulli.pmf(range(3), p=0.3): {}". format(bernoulli.pmf(range(3), p=0.3))) print( "\nBernoulli cdf w/ scipy.stats.bernoulli.cdf([0, 0.5, 1, 1.5], p=0.3): {}" .format(bernoulli.cdf([0, 0.5, 1, 1.5], p=0.3))) # plot Bernoulli plt.stem([-0.2, 0, 1, 1.2], bernoulli.pmf([-0.2, 0, 1, 1.2], p=.3)) plt.plot(np.linspace(-0.1, 1.1, 1200), bernoulli.cdf(np.linspace(-0.1, 1.1, 1200), p=0.3), 'g') plt.xlim([-0.1, 1.1]) plt.ylim([-0.2, 1.1]) plt.show() # generate Bernoulli samples print( "\nBernoulli samples w/ scipy.stats.bernoulli.rvs(size=10, p=.3): {}". format(bernoulli.rvs(size=10, p=.3))) plt.hist(bernoulli.rvs(size=10, p=.3), density=True) plt.show() return None
def cdf(self, x: float): """Find the CDF for a certain x value. Args: x (float): The value for which the CDF is needed. """ return bernoulli.cdf(x, self.p)
def get_bernoulli(p, size): rv = bernoulli(p) x = np.arange(0, np.minimum(rv.dist.b, 3)) h = plt.vlines(x, 0, rv.pmf(x), lw=2) prb = bernoulli.cdf(x, p) h = plt.semilogy(np.abs(x - bernoulli.ppf(prb, p)) + 1e-20) labels = bernoulli.rvs(p, size=size).tolist() return labels
def cdf(self): """ Compute the cumulative distribution function. Returns: -------- cdf : float """ return bernoulli.cdf(self.__r, self.__p)
def cdf(self, y, f): r""" Cumulative density function of the likelihood. Parameters ---------- y: ndarray query quantiles, i.e.\ :math:`P(Y \leq y)`. f: ndarray latent function from the GLM prior (:math:`\mathbf{f} = \boldsymbol\Phi \mathbf{w}`) Returns ------- cdf: ndarray Cumulative density function evaluated at y. """ return bernoulli.cdf(y, expit(f))
def test_bernoulli(): # Test we can at match a Bernoulli distribution from scipy p = 0.5 dist = lk.Bernoulli() x = np.array([0, 1]) p1 = bernoulli.logpmf(x, p) p2 = dist.loglike(x, p) np.allclose(p1, p2) p1 = bernoulli.cdf(x, p) p2 = dist.cdf(x, p) np.allclose(p1, p2)
plt.ylabel("Probability") sns.despine() plot_simulation(result) from scipy.stats import bernoulli brv = bernoulli(p=0.3) brv.rvs(size=20) event_space=[0,1] plt.figure(figsize=(12,8)) colors=sns.color_palette() for i, p in enumerate([0.1, 0.2, 0.5, 0.7]): ax = plt.subplot(1, 4, i+1) plt.bar(event_space, bernoulli.pmf(event_space, p), label=p, color = colors[i], alpha = 0.5) plt.plot(event_space, bernoulli.cdf(event_space, p), color = colors[i], alpha=0.5) ax.xaxis.set_ticks(event_space) plt.ylim((0,1)) plt.legend(loc=0) if i == 0: plt.ylabel("PDF at $k$") plt.tight_layout() CDF = lambda x: np.float(np.sum(result < x))/result.shape[0] for votes in [200, 300, 320, 340, 360, 400, 500]: print "Obama Win CDF at votes=", votes, " is ", CDF(votes) votelist = np.arange(0,540, 5) plt.plot(votelist, [CDF(v) for v in votelist], '.-')
from scipy.stats import bernoulli, poisson, uniform, expon, erlang, norm, triang # Bernoulli p = 0.5 x = 1 # Generate a probability using the PMF print(bernoulli.pmf(x, p)) # 0.5 # Generate a probability using the CDF print(bernoulli.cdf(x, p)) # 1.0 # Generate three Bernoulli random numbers print(bernoulli.rvs(p, size=3)) # [0 1 0] # Poisson lmda = 2 x = 5 print(poisson.pmf(x, lmda)) print(poisson.cdf(x, lmda)) print(poisson.rvs(lmda, size=3)) # Uniform a = 3 b = 10 x = 10 print(uniform.pdf(x, loc=a, scale=(b - a))) # = 1 / 7 print(uniform.cdf(x, loc=a, scale=(b - a))) # = 1.0 print(uniform.rvs(loc=3, scale=(b - a), size=3)) # Exponential mu = 2 x = 2 print(expon.pdf(x, scale=(1 / mu)))
from scipy.stats import bernoulli import numpy as np import matplotlib.pyplot as plt p = 0.8 k1 = 0 k2 = 1 k = np.linspace(k1, k2, 100) temp1 = bernoulli.cdf(k, p) temp2 = bernoulli.pmf(k1, p) temp3 = bernoulli.pmf(k2, p) print(temp1) print(temp2) print(temp3) plt.plot(k, temp1, 'o-', color='orange') plt.plot(p, temp2, 'o-', color='crimson') plt.plot(p, temp3, 'o-', color='crimson') plt.xlabel('$x$') plt.ylabel('$y$') plt.grid() plt.show()
brv.rvs(size=20) # In[20]: event_space = [0, 1] plt.figure(figsize=(12, 8)) colors = sns.color_palette() for i, p in enumerate([0.1, 0.2, 0.5, 0.7]): ax = plt.subplot(1, 4, i + 1) plt.bar(event_space, bernoulli.pmf(event_space, p), label=p, color=colors[i], alpha=0.5) plt.plot(event_space, bernoulli.cdf(event_space, p), color=colors[i], alpha=0.5) ax.xaxis.set_ticks(event_space) plt.ylim((0, 1)) plt.legend(loc=0) if i == 0: plt.ylabel("PDF at $k$") plt.tight_layout() # In[21]: CDF = lambda x: np.float(np.sum(result < x)) / result.shape[0] for votes in [200, 300, 320, 340, 360, 400, 500]:
import seaborn as sns # ### Bernoulli Distribution # In[2]: #Bernoulli Distribution from scipy.stats import bernoulli p = 0.7 x = np.arange(bernoulli.ppf(0.01, p), bernoulli.ppf( 0.99, p)) #Percent Point Function (inverse of cdf — percentiles) print("Mean : ", bernoulli.stats(p, moments='m')) print("Variance : ", bernoulli.stats(p, moments='v')) print("Prob. Mass Func. : ", bernoulli.pmf(x, p).item()) print("Cum. Density Func.: ", bernoulli.cdf(x, p).item()) fig = plt.figure(figsize=(20, 10)) plt.subplot(221) plt.plot(x, bernoulli.pmf(x, p), 'ro', ms=8, label='PMF=(1-p)') plt.plot(1 - x, 1 - bernoulli.pmf(x, p), 'go', ms=8, label='PMF=p') plt.vlines(x, 0, bernoulli.pmf(x, p), colors='r', lw=5, alpha=0.5) plt.vlines(1 - x, 0, 1 - bernoulli.pmf(x, p), colors='g', lw=5, alpha=0.5) plt.xlabel("Sample Space of Bernoulli Distribution", fontsize=14) plt.ylabel("PMF", fontsize=14) plt.title("Probability Distribution of Bernoulli(p=0.7) Distribution", fontsize=16) plt.xticks(np.arange(0, 2, 1)) plt.yticks(np.arange(0, 1.1, 0.1)) plt.legend(loc='best', shadow=True)
p = 0.7 print("Probability Mass Function = ", bernoulli.pmf(x, p)) #Plot the graph for Probability Mass Function(PMF): x = [0, 1] p = 0.7 plt.scatter(x, bernoulli.pmf(x, p), label="PMF") plt.title("Probability Mass Function") plt.xlabel("Data Points") plt.ylabel("Probability") plt.legend() #Get Cumulative Density Function(CDF): x = [0, 1] p = 0.7 print("Cumulative Density Function = ", bernoulli.cdf(x, p)) #Plot the Cumulative Density Function(CDF): x = [0, 1] p = 0.7 plt.scatter(x, bernoulli.cdf(x, p), label="CDF") plt.title("Cumulative Density Function") plt.xlabel("Data Points") plt.ylabel("Probability") plt.legend() #Plot the bar graph for PMF: x = [0, 1] p = 0.7 plt.bar(x, bernoulli.pmf(x, p), width=0.1, color=["r", "b"]) plt.title("Probability Mass Function")
from scipy.stats import bernoulli import numpy as np k = 3 p = 0.4 expect = bernoulli.expect(args=(p, ), loc=0) mean = bernoulli.mean(p) var = bernoulli.var(p) sigma = bernoulli.std(p) pmf = bernoulli.pmf(k, p, loc=0) cdf = bernoulli.cdf(k, p, loc=0) print('expected = ', expect) print('mean = ', mean) print('variance = ', var) print('std. dev. = ', sigma) print('pmf = ', pmf) print('cdf = ', cdf)
def cdf(self, n, p): cdf = bernoulli.cdf(self, n, p) return cdf
from scipy.stats import bernoulli import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(1, 1) # Calculate a few first moments: p = 0.3 mean, var, skew, kurt = bernoulli.stats(p, moments='mvsk') # Display the probability mass function (pmf): x = np.arange(bernoulli.ppf(0.01, p), bernoulli.ppf(0.99, p)) ax.plot(x, bernoulli.pmf(x, p), 'bo', ms=8, label='bernoulli pmf') ax.vlines(x, 0, bernoulli.pmf(x, p), colors='b', lw=5, alpha=0.5) # Freeze the distribution and display the frozen pmf: rv = bernoulli(p) ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1, label='frozen pmf') ax.legend(loc='best', frameon=False) plt.show() # Check accuracy of cdf and ppf: prob = bernoulli.cdf(x, p) np.allclose(x, bernoulli.ppf(prob, p)) # Generate random numbers: r = bernoulli.rvs(p, size=1000)
def _cdf(self, p1): cdf = bernoulli.cdf([0, 1], p1) * (1 << self.precision) cdf = np.insert(np.around(cdf).astype(int), 0, 0) # Prevent overflow. cdf[1] = np.clip(cdf[1], 1, (1 << self.precision) - 1) return cdf