Fitting with prior distribution#

In this example, we demonstrate how to update the prior distribution with data to obtain a posterior distribution. The main assumption is that the posterior distribution belongs to the same probability distribution family as the prior. In that case, the prior and posterior are called conjugate distributions.

This functionality supports three distribution types: normal, log_normal and bernoulli.

We begin by importing the required classes:

[1]:
from probabilistic_library import Stochast, DistributionType

Define prior#

We define the prior distribution:

[2]:
prior = Stochast()
prior.distribution = DistributionType.normal
prior.mean = 3.5
prior.deviation = 0.2

plt = prior.get_plot()
plt.title("Prior distribution")
[2]:
Text(0.5, 1.0, 'Prior distribution')
../_images/_examples_fitting_with_prior_distribution_3_1.png

Fit distribution#

Suppose we have a set of observations, and we fit a distribution to these data. The distribution must be of the same type as the prior distribution:

[3]:
data = [-0.1, 0.0, -0.2, -4.0, -0.1, 0.1, 0.2, -2.0]

variable = Stochast()
variable.distribution = DistributionType.normal
variable.fit(data)

variable.print()
plt = variable.get_plot()
plt.title("Fitted distribution")
Variable:
  distribution = normal
Definition:
  location = -0.7625
  scale = 1.486
Derived values:
  mean = -0.7625
  deviation = 1.486
  variation = 1.949
[3]:
Text(0.5, 1.0, 'Fitted distribution')
../_images/_examples_fitting_with_prior_distribution_5_2.png

Derive posterior#

Then, we derive the posterior distribution using the fit_prior() method:

[4]:
variable.fit_prior(prior, data)

variable.print()
plt = variable.get_plot()
plt.title("Posterior distribution")
plt.show()
Variable:
  distribution = normal
Definition:
  location = 2.961
  scale = 0.1869
Derived values:
  mean = 2.961
  deviation = 0.1869
  variation = 0.06314
[4]:
Text(0.5, 1.0, 'Posterior distribution')
../_images/_examples_fitting_with_prior_distribution_7_2.png