{"id":62118,"date":"2024-04-30T10:44:56","date_gmt":"2024-04-30T10:44:56","guid":{"rendered":"https:\/\/www.askpython.com\/?p=62118"},"modified":"2025-04-10T20:28:57","modified_gmt":"2025-04-10T20:28:57","slug":"bayesian-inference-in-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/bayesian-inference-in-python","title":{"rendered":"Bayesian Inference in Python: A Comprehensive Guide with Examples"},"content":{"rendered":"\n<p>Data-driven decision-making has become essential across various fields, from finance and economics to medicine and engineering. Understanding probability and statistics is crucial for making informed choices today. Bayesian inference, a powerful tool in probabilistic reasoning, allows us to update our beliefs about an event based on new evidence.<\/p>\n\n\n\n<p>Bayes&#8217;s theorem, a fundamental concept in probability theory, forms the foundation of Bayesian inference. This theorem provides a way to calculate the probability of an event occurring given prior knowledge and observed data. Combining our initial beliefs with the likelihood of the evidence, we can arrive at a more accurate posterior probability.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><em>Bayesian inference is a statistical method based on Bayes&#8217;s theorem, which updates the probability of an event as new data becomes available. It is widely used in various fields, such as finance, medicine, and engineering, to make predictions and decisions based on prior knowledge and observed data. In Python, Bayesian inference can be implemented using libraries like NumPy and Matplotlib to generate and visualize posterior distributions.<\/em><\/p>\n<\/blockquote>\n\n\n\n<p>This article will explore Bayesian inference and its implementation using Python, a popular programming language for data analysis and scientific computing. We will start by understanding the fundamentals of Bayes&#8217;s theorem and formula, then move on to a step-by-step guide on implementing Bayesian inference in Python. Along the way, we will discuss a real-world example of predicting website conversion rates to illustrate the practical application of this powerful technique.<\/p>\n\n\n\n<p><strong><em>Recommended: <a href=\"https:\/\/www.askpython.com\/python\/simulating-blackjack-card-counting-python\">Python and Probability: Simulating Blackjack Card Counting with Python Code<\/a><\/em><\/strong><\/p>\n\n\n\n<p><strong><em>Recommended: <a href=\"https:\/\/www.askpython.com\/python\/examples\/joint-probability-distribution\">Understanding Joint Probability Distribution with Python<\/a><\/em><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is Bayesian Inference?<\/h2>\n\n\n\n<p>Bayesian inference is based on Bayes&#8217;s theorem, which is based on the prior probability of an event. As events happen, the probability of the event keeps updating. Let us look at the formula of Baye&#8217;s theorem.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"585\" height=\"182\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Bayes-Theorem-formula.png\" alt=\"Bayes Theorem Formula\" class=\"wp-image-62160\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Bayes-Theorem-formula.png 585w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Bayes-Theorem-formula-300x93.png 300w\" sizes=\"auto, (max-width: 585px) 100vw, 585px\" \/><figcaption class=\"wp-element-caption\"><strong><em>Bayes Theorem Formula<\/em><\/strong><\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Implementing Bayesian Inference in Python<\/h2>\n\n\n\n<p>Let us try to implement the same in Python with the code below.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Generate some synthetic data\nnp.random.seed(42)\ntrue_mu = 5\ntrue_sigma = 2\ndata = np.random.normal(true_mu, true_sigma, size=100)\n\n# Define the prior hyperparameters\nprior_mu_mean = 0\nprior_mu_precision = 1  # Variance = 1 \/ precision\nprior_sigma_alpha = 2\nprior_sigma_beta = 2  # Beta = alpha \/ beta\n\n# Update the prior hyperparameters with the data\nposterior_mu_precision = prior_mu_precision + len(data) \/ true_sigma**2\nposterior_mu_mean = (prior_mu_precision * prior_mu_mean + np.sum(data)) \/ posterior_mu_precision\n\nposterior_sigma_alpha = prior_sigma_alpha + len(data) \/ 2\nposterior_sigma_beta = prior_sigma_beta + np.sum((data - np.mean(data))**2) \/ 2\n\n# Calculate the posterior parameters\nposterior_mu = np.random.normal(posterior_mu_mean, 1 \/ np.sqrt(posterior_mu_precision), size=10000)\nposterior_sigma = np.random.gamma(posterior_sigma_alpha, 1 \/ posterior_sigma_beta, size=10000)\n\n# Plot the posterior distributions\nplt.figure(figsize=(10, 4))\nplt.subplot(1, 2, 1)\nplt.hist(posterior_mu, bins=30, density=True, color=&#039;skyblue&#039;, edgecolor=&#039;black&#039;)\nplt.title(&#039;Posterior distribution of $\\mu$&#039;)\nplt.xlabel(&#039;$\\mu$&#039;)\nplt.ylabel(&#039;Density&#039;)\n\nplt.subplot(1, 2, 2)\nplt.hist(posterior_sigma, bins=30, density=True, color=&#039;lightgreen&#039;, edgecolor=&#039;black&#039;)\nplt.title(&#039;Posterior distribution of $\\sigma$&#039;)\nplt.xlabel(&#039;$\\sigma$&#039;)\nplt.ylabel(&#039;Density&#039;)\n\nplt.tight_layout()\nplt.show()\n\n# Calculate summary statistics\nmean_mu = np.mean(posterior_mu)\nstd_mu = np.std(posterior_mu)\nprint(&quot;Mean of mu:&quot;, mean_mu)\nprint(&quot;Standard deviation of mu:&quot;, std_mu)\n\nmean_sigma = np.mean(posterior_sigma)\nstd_sigma = np.std(posterior_sigma)\nprint(&quot;Mean of sigma:&quot;, mean_sigma)\nprint(&quot;Standard deviation of sigma:&quot;, std_sigma)\n\n<\/pre><\/div>\n\n\n<p>Let us look at the output of the same.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"989\" height=\"390\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Bayes-Theorem-plot.png\" alt=\"Bayes Theorem Plot\" class=\"wp-image-62161\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Bayes-Theorem-plot.png 989w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Bayes-Theorem-plot-300x118.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Bayes-Theorem-plot-768x303.png 768w\" sizes=\"auto, (max-width: 989px) 100vw, 989px\" \/><figcaption class=\"wp-element-caption\"><strong><em>Bayes Theorem Plot<\/em><\/strong><\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"607\" height=\"117\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Bayes-theorem-output.png\" alt=\"Bayes Theorem Output\" class=\"wp-image-62163\"\/><figcaption class=\"wp-element-caption\"><strong><em>Bayes Theorem Output<\/em><\/strong><\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Real-World Example: Predicting Website Conversion Rates with Bayesian Inference<\/h2>\n\n\n\n<p>Let us now look at the case of a website. We are trying to predict how many people will buy the product to the ratio of the number of visitors. We have also created some parameters.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Observed data\nnum_visitors = 1000  # Total number of visitors to the website\nnum_conversions = 50  # Number of conversions (desired actions)\n\n# Prior hyperparameters for the Beta distribution\nprior_alpha = 1  # Shape parameter\nprior_beta = 1   # Shape parameter\n\n# Update the prior with the observed data to get the posterior parameters\nposterior_alpha = prior_alpha + num_conversions\nposterior_beta = prior_beta + (num_visitors - num_conversions)\n\n# Generate samples from the posterior Beta distribution\nposterior_samples = np.random.beta(posterior_alpha, posterior_beta, size=10000)\n\n# Plot the posterior distribution\nplt.figure(figsize=(8, 6))\nplt.hist(posterior_samples, bins=30, density=True, color=&#039;skyblue&#039;, edgecolor=&#039;black&#039;, alpha=0.7)\nplt.title(&#039;Posterior Distribution of Conversion Rate&#039;)\nplt.xlabel(&#039;Conversion Rate&#039;)\nplt.ylabel(&#039;Density&#039;)\nplt.xlim(0, 0.1)  # Limiting x-axis to focus on conversion rates close to zero\nplt.show()\n\n# Calculate summary statistics\nmean_conversion_rate = posterior_alpha \/ (posterior_alpha + posterior_beta)\nmode_conversion_rate = (posterior_alpha - 1) \/ (posterior_alpha + posterior_beta - 2)  # Mode of the Beta distribution\n\nprint(&quot;Mean conversion rate:&quot;, mean_conversion_rate)\nprint(&quot;Mode conversion rate:&quot;, mode_conversion_rate)\n\n<\/pre><\/div>\n\n\n<p>Let us look at the output of the above code and try to deduce some information from it.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"702\" height=\"547\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Bayesian-Inference-output.png\" alt=\"Bayesian Inference Output\" class=\"wp-image-62167\" style=\"width:702px;height:auto\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Bayesian-Inference-output.png 702w, https:\/\/www.askpython.com\/wp-content\/uploads\/2024\/04\/Bayesian-Inference-output-300x234.png 300w\" sizes=\"auto, (max-width: 702px) 100vw, 702px\" \/><figcaption class=\"wp-element-caption\"><strong><em>Bayesian Inference Output<\/em><\/strong><\/figcaption><\/figure>\n\n\n\n<p>According to our predictions, the probability of conversion is around 5%.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Here you go! Now, you know a lot more about Bayesian inference. In this article, we learned what Bayesian inference is and also touched upon how to implement it in the Python programming language. We also learned about a very simple case study where we calculated the probability of customers&#8217; conversions if they visited a particular website. Bayesian inference, as mentioned, is also used heavily in the fields of finance, economics, and engineering.<\/p>\n\n\n\n<p>Hope you enjoyed reading it!!<\/p>\n\n\n\n<p><strong><em>Recommended: <a href=\"https:\/\/www.askpython.com\/python\/examples\/monte-carlo-simulation\">Monte-Carlo Simulation to find the probability of Coin toss in python<\/a><\/em><\/strong><\/p>\n\n\n\n<p><strong><em>Recommended: <a href=\"https:\/\/www.askpython.com\/python\/examples\/detect-fake-dollar-bills-python\">5 Ways to Detect Fake Dollar Bills Using Python Machine Learning<\/a><\/em><\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Data-driven decision-making has become essential across various fields, from finance and economics to medicine and engineering. Understanding probability and statistics is crucial for making informed choices today. Bayesian inference, a powerful tool in probabilistic reasoning, allows us to update our beliefs about an event based on new evidence. Bayes&#8217;s theorem, a fundamental concept in probability [&hellip;]<\/p>\n","protected":false},"author":80,"featured_media":63864,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-62118","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/62118","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/80"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=62118"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/62118\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/63864"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=62118"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=62118"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=62118"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}