Example #1
0
def plot_gamma_exponential():

    ge = GammaExponential(alpha=10, beta=5, n=100, x_mean=0.3)
    ax = new_axes()
    ge.prior().plot(x=rates, color='r', ax=ax)
    ge.posterior().plot(x=rates, color='g', ax=ax)
    ax.legend()
    plt.show()
    ax = new_axes()
    ge.pdf().plot(x=durations, ax=ax)
    ax.legend()
    plt.show()
    def plot(self, k: Iterable[int], color: str = 'C0', kind: str = 'bar', ax: Axes = None,
             **kwargs) -> Axes:
        """
        Plot the function.

        :param k: Range of values of k to plot p(k) over.
        :param color: Optional color for the series.
        :param kind: Kind of plot e.g. 'bar', 'line'.
        :param ax: Optional matplotlib axes to plot on.
        :param kwargs: Additional arguments for the matplotlib plot function.
        """
        data: Series = self.at(k)
        ax = ax or new_axes()

        # special kwargs
        vlines = None
        if 'vlines' in kwargs.keys():
            vlines = kwargs.pop('vlines')

        if self._name == 'PMF':
            data.plot(kind=kind, label=self._parent.label, color=color,
                      ax=ax, **kwargs)
        elif self._name == 'CDF':
            data.plot(kind='line', label=self._parent.label, color=color,
                      drawstyle='steps-post', ax=ax,
                      **kwargs)
        else:
            raise ValueError('plot not implemented for {}'.format(self._name))
        if vlines:
            ax.vlines(x=k, ymin=0, ymax=data.values, color=color)
        ax.set_xlabel(self._parent.x_label)
        ax.set_ylabel(self._name)
        return ax
Example #3
0
def plot_wikipedia_pmfs():
    """
    https://en.wikipedia.org/wiki/Binomial_distribution#/media/File:Binomial_distribution_pmf.svg
    """
    ax = new_axes()
    Binomial(n=20, p=0.5).plot(k=k_wiki,
                               kind='line',
                               color='blue',
                               ax=ax,
                               ls='',
                               marker='d')
    Binomial(n=20, p=0.7).plot(k=k_wiki,
                               kind='line',
                               color='lightgreen',
                               ax=ax,
                               ls='',
                               marker='s')
    Binomial(n=40, p=0.5).plot(k=k_wiki,
                               kind='line',
                               color='red',
                               ax=ax,
                               ls='',
                               marker='o')
    ax.set_ylim(0, 0.25)
    ax.set_title('Probability mass function')
    ax.legend(loc='upper right')
    plt.show()
Example #4
0
def plot_parameters():

    ax = new_axes()
    dist.prior().plot(x=x, color='r', ax=ax)
    dist.posterior().plot(x=x, color='g', ax=ax)
    ax.legend()
    plt.show()
Example #5
0
    def plot(self,
             x: Iterable,
             kind: str = 'line',
             color: str = 'C0',
             ax: Axes = None,
             **kwargs) -> Axes:
        """
        Plot the function.

        :param x: Range of values of x to plot p(x) over.
        :param kind: Kind of plot e.g. 'bar', 'line'.
        :param color: Optional color for the series.
        :param ax: Optional matplotlib axes to plot on.
        :param kwargs: Additional arguments for the matplotlib plot function.
        """
        data: Series = self.at(x)
        ax = ax or new_axes()
        if self._name in ('PDF', 'CDF', 'log(PDF)'):
            data.plot(kind=kind,
                      label=self._parent.label,
                      color=color,
                      ax=ax,
                      **kwargs)
        else:
            raise ValueError('plot not implemented for {}'.format(self._name))
        ax.set_xlabel(self._parent.x_label)
        ax.set_ylabel(self._name)
        return ax
Example #6
0
def plot_wikipedia_cdfs():

    ax = new_axes()
    InvGamma(alpha=1, beta=1).cdf().plot(x=x, color='red', ax=ax)
    InvGamma(alpha=2, beta=1).cdf().plot(x=x, color='green', ax=ax)
    InvGamma(alpha=3, beta=1).cdf().plot(x=x, color='blue', ax=ax)
    InvGamma(alpha=3, beta=0.5).cdf().plot(x=x, color='cyan', ax=ax)
    ax.legend()
    plt.show()
Example #7
0
def plot_wikipedia_pdfs():
    """
    https://en.wikipedia.org/wiki/Exponential_distribution#/media/File:Exponential_probability_density.svg
    """
    ax = new_axes()
    Exponential(lambda_=0.5).plot(x=x, color='orange', ax=ax)
    Exponential(lambda_=1).plot(x=x, color='purple', ax=ax)
    Exponential(lambda_=1.5).plot(x=x, color='lightblue', ax=ax)
    ax.set_ylim(0, 1.5)
    plt.show()
Example #8
0
def plot_predictions():

    ax = new_axes()
    predicted = dist.rvs(100000)
    ax.hist(predicted, bins=100, density=True, label='PPD samples')
    x_actual = arange(predicted.min(), predicted.max(), 0.01)
    actual = norm(loc=mu, scale=sigma).pdf(x_actual)
    ax.plot(x_actual, actual, label='True Distribution')
    ax.legend()
    plt.show()
Example #9
0
def plot_wikipedia_cdfs():
    """
    https://en.wikipedia.org/wiki/Lomax_distribution#/media/File:LomaxCDF.png
    """
    ax = new_axes()
    Lomax(lambda_=1, alpha=2).cdf().plot(x=x, color='blue', ax=ax)
    Lomax(lambda_=2, alpha=2).cdf().plot(x=x, color='green', ax=ax)
    Lomax(lambda_=4, alpha=1).cdf().plot(x=x, color='red', ax=ax)
    Lomax(lambda_=6, alpha=1).cdf().plot(x=x, color='orange', ax=ax)
    plt.show()
Example #10
0
def plot_wikipedia_pdfs():
    """
    https://en.wikipedia.org/wiki/Laplace_distribution#/media/File:Laplace_pdf_mod.svg
    """
    ax = new_axes()
    Laplace(mu=0, b=1).plot(x=x, color='red', ax=ax)
    Laplace(mu=0, b=2).plot(x=x, color='black', ax=ax)
    Laplace(mu=0, b=4).plot(x=x, color='blue', ax=ax)
    Laplace(mu=-5, b=4).plot(x=x, color='green', ax=ax)
    ax.legend(loc='upper right')
    plt.show()
Example #11
0
def plot_wikipedia_pdfs():
    """
    https://en.wikipedia.org/wiki/Normal_distribution#/media/File:Normal_Distribution_PDF.svg
    """
    ax = new_axes()
    Normal(mu=0, sigma_sq=0.2).plot(x=x, color='blue', ax=ax)
    Normal(mu=0, sigma_sq=1.0).plot(x=x, color='red', ax=ax)
    Normal(mu=0, sigma_sq=5.0).plot(x=x, color='orange', ax=ax)
    Normal(mu=-2, sigma_sq=0.5).plot(x=x, color='green', ax=ax)
    ax.legend(loc='upper right')
    plt.show()
Example #12
0
def plot_wikipedia_cdfs():
    """
    https://en.wikipedia.org/wiki/Beta-binomial_distribution#/media/File:Beta-binomial_cdf.png
    """
    ax = new_axes(width=10, height=10)
    BetaBinomial(alpha=0.2, beta=0.25, n=10).cdf().plot(k=k, color='black', ax=ax)
    BetaBinomial(alpha=0.7, beta=2, n=10).cdf().plot(k=k, color='red', ax=ax)
    BetaBinomial(alpha=2, beta=2, n=10).cdf().plot(k=k, color='green', ax=ax)
    BetaBinomial(alpha=600, beta=400, n=10).cdf().plot(k=k, color='blue', ax=ax)
    ax.legend()
    plt.show()
Example #13
0
def plot_wikipedia_cdfs():
    """
    https://en.wikipedia.org/wiki/Poisson_distribution#/media/File:Poisson_pmf.svg
    """
    ax = new_axes(width=10, height=10)
    Poisson(lambda_=1).cdf().plot(k=k_wikipedia, color='gray', mfc='orange', marker='o', ax=ax)
    Poisson(lambda_=4).cdf().plot(k=k_wikipedia, color='gray', mfc='purple', marker='o', ax=ax)
    Poisson(lambda_=10).cdf().plot(k=k_wikipedia, color='gray', mfc='lightblue', marker='o', ax=ax)
    ax.set_title('Cumulative distribution function')
    ax.legend(loc='lower right')
    plt.show()
Example #14
0
def plot_wikipedia_cdfs():
    """
    https://en.wikipedia.org/wiki/Student%27s_t-distribution#/media/File:Student_t_cdf.svg
    """
    ax = new_axes()
    StudentsT(nu=1).cdf().plot(x=x_wikipedia_1, color='orange', ax=ax)
    StudentsT(nu=2).cdf().plot(x=x_wikipedia_1, color='purple', ax=ax)
    StudentsT(nu=5).cdf().plot(x=x_wikipedia_1, color='lightblue', ax=ax)
    StudentsT(nu=1e9).cdf().plot(x=x_wikipedia_1, color='black', ax=ax)
    ax.legend(loc='lower right')
    plt.show()
Example #15
0
def plot_wikipedia_pmfs():
    """
    https://en.wikipedia.org/wiki/Poisson_distribution#/media/File:Poisson_pmf.svg
    """
    ax = new_axes(width=10, height=10)
    Poisson(lambda_=1).plot(k=k_wikipedia, kind='line', color='gray', mfc='orange', marker='o', ax=ax)
    Poisson(lambda_=4).plot(k=k_wikipedia, kind='line', color='gray', mfc='purple', marker='o', ax=ax)
    Poisson(lambda_=10).plot(k=k_wikipedia, kind='line', color='gray', mfc='lightblue', marker='o', ax=ax)
    ax.set_ylim(0, 0.4)
    ax.set_title('Probability mass function')
    ax.legend(loc='upper right')
    plt.show()
Example #16
0
def plot_wikipedia_cdfs():
    """
    https://en.wikipedia.org/wiki/Beta_distribution#/media/File:Beta_distribution_cdf.svg
    """
    ax = new_axes(width=10, height=10)
    Beta(0.5, 0.5).cdf().plot(x=x, color='red', ax=ax)
    Beta(5, 1).cdf().plot(x=x, color='blue', ax=ax)
    Beta(1, 3).cdf().plot(x=x, color='green', ax=ax)
    Beta(2, 2).cdf().plot(x=x, color='purple', ax=ax)
    Beta(2, 5).cdf().plot(x=x, color='orange', ax=ax)
    ax.set_title('Cumulative distribution function')
    ax.legend(loc='upper left')
    plt.show()
Example #17
0
def plot_wikipedia_pdfs():
    """
    https://en.wikipedia.org/wiki/Beta_distribution#/media/File:Beta_distribution_pdf.svg
    """
    ax = new_axes(width=10, height=10)
    Beta(0.5, 0.5).pdf().plot(x=x, color='red', ax=ax)
    Beta(5, 1).pdf().plot(x=x, color='blue', ax=ax)
    Beta(1, 3).pdf().plot(x=x, color='green', ax=ax)
    Beta(2, 2).pdf().plot(x=x, color='purple', ax=ax)
    Beta(2, 5).pdf().plot(x=x, color='orange', ax=ax)
    ax.set_ylim(0, 2.5)
    ax.set_title('Probability density function')
    ax.legend(loc='upper center')
    plt.show()
Example #18
0
def plot_wikipedia_cdfs():
    """
    https://en.wikipedia.org/wiki/Gamma_distribution#/media/File:Gamma_distribution_cdf.svg
    """
    ax = new_axes()
    Gamma.from_k_theta(k=1, theta=2).cdf().plot(x=x, color='red', ax=ax)
    Gamma.from_k_theta(k=2, theta=2).cdf().plot(x=x, color='orange', ax=ax)
    Gamma.from_k_theta(k=3, theta=2).cdf().plot(x=x, color='yellow', ax=ax)
    Gamma.from_k_theta(k=5, theta=1).cdf().plot(x=x, color='green', ax=ax)
    Gamma.from_k_theta(k=9, theta=0.5).cdf().plot(x=x, color='black', ax=ax)
    Gamma.from_k_theta(k=7.5, theta=1).cdf().plot(x=x, color='blue', ax=ax)
    Gamma.from_k_theta(k=0.5, theta=1).cdf().plot(x=x, color='purple', ax=ax)
    ax.set_ylim(0, 1)
    ax.legend(loc='lower right')
    plt.show()
Example #19
0
    def plot_2d(self, x1: Union[Iterable, ndarray], x2: Union[Iterable, ndarray],
                color_map: str = 'viridis', ax: Axes = None) -> Axes:
        """
        Plot a 2-dimensional function as a grid heat-map.

        :param x1: Range of values of x1 to plot p(x1, x2) over.
        :param x2: Range of values of x2 to plot p(x1, x2) over.
        :param color_map: Optional colormap for the heat-map.
        :param ax: Optional matplotlib axes to plot on.
        """
        x1_grid, x2_grid = meshgrid(x1, x2)
        x1_x2 = dstack((x1_grid, x2_grid))
        f = self._method(x1_x2)
        ax = ax or new_axes()
        ax.contourf(x1_grid, x2_grid, f, cmap=color_map)
        ax.set_xlabel('x1')
        ax.set_ylabel('x2')
        return ax
Example #20
0
def plot_wikipedia_cdfs():
    """
    https://en.wikipedia.org/wiki/Binomial_distribution#/media/File:Binomial_distribution_cdf.svg
    """
    ax = new_axes()
    Binomial(n=20, p=0.5).cdf().plot(k=k_wiki,
                                     kind='line',
                                     color='blue',
                                     ax=ax)
    Binomial(n=20, p=0.7).cdf().plot(k=k_wiki,
                                     kind='line',
                                     color='lightgreen',
                                     ax=ax)
    Binomial(n=40, p=0.5).cdf().plot(k=k_wiki, kind='line', color='red', ax=ax)
    ax.set_ylim(0, 1.0)
    ax.set_title('Cumulative distribution function')
    ax.legend(loc='upper right')
    plt.show()
Example #21
0
    def plot_simplex(self, num_contours: int = 100, num_sub_div: int = 8,
                     color_map: str = 'viridis', border: bool = True, ax: Axes = None) -> Axes:
        """
        Plot a 3-dimensional functions as a simplex heat-map.

        :param num_contours: The number of levels of contours to plot.
        :param num_sub_div: Number of recursive subdivisions to create.
        :param color_map: Optional colormap for the plot.
        :param border: Whether to plot a border around the simplex heatmap.
        :param ax: Optional matplotlib axes to plot on.
        """

        corners = array([[0, 0], [1, 0], [0.5, 0.75 ** 0.5]])
        triangle = Triangulation(corners[:, 0], corners[:, 1])
        mid_points = [
            (corners[(i + 1) % 3] + corners[(i + 2) % 3]) / 2
            for i in range(3)
        ]

        def to_barycentric(cartesian):
            """
            Converts 2D Cartesian to barycentric coordinates.

            :param cartesian: A length-2 sequence containing the x and y value.
            """
            s = [(corners[i] - mid_points[i]).dot(cartesian - mid_points[i]) / 0.75
                 for i in range(3)]
            s_clipped = clip(a=s, a_min=0, a_max=1)
            return s_clipped / norm(s_clipped, ord=1)

        refiner = UniformTriRefiner(triangle)
        tri_mesh = refiner.refine_triangulation(subdiv=num_sub_div)
        f = [self._method(to_barycentric(xy))
             for xy in zip(tri_mesh.x, tri_mesh.y)]
        ax = ax or new_axes()
        ax.tricontourf(tri_mesh, f, num_contours, cmap=color_map)
        ax.set_aspect('equal')
        ax.set_xlim(0, 1)
        ax.set_ylim(0, 0.75 ** 0.5)
        ax.set_axis_off()
        if border:
            ax.triplot(triangle, linewidth=1)

        return ax
Example #22
0
    def plot(self,
             x: ndarray,
             color: str = 'C1',
             ax: Optional[Axes] = None) -> Axes:
        """
        Plot the prior probability of the parameter θ given the priors α, β

        `p(x|α,β)`

        :param x: vector of possible `x`s
        :param color: Optional color for the series.
        :param ax: Optional matplotlib axes
        :rtype: Axes
        """
        ax = ax or new_axes()
        self._distribution.pdf().at(x).plot(kind='line',
                                            label=self._label,
                                            color=color or 'C0',
                                            ax=ax)
        ax.set_xlabel(self._x_label)
        ax.set_ylabel(self._y_label)
        ax.legend()
        return ax
Example #23
0
    def plot(self,
             x: Union[Iterable[Iterable], ndarray],
             color: str = 'C0',
             ax: Axes = None) -> Axes:
        """
        Plot the function.

        :param x: Range of values of x to plot p(x) over.
        :param color: Optional color for the series.
        :param ax: Optional matplotlib axes to plot on.
        """
        x = array(x)
        data = self.at(x)
        if x.ndim != 2:
            raise ValueError('x must have 2 dimensions: [num_points, K]')
        ax = ax or new_axes()
        if self._num_dims > 2:
            data = data.sort_values(ascending=False)
        data.plot.bar(color=color, label=str(self._parent), ax=ax)
        ax.set_xlabel('x')
        ax.set_ylabel(self._name)
        ax.legend(loc='upper right')
        return ax