SlideShare uma empresa Scribd logo
1 de 30
Baixar para ler offline
14/10/2017
Bayesian analysis in Python
Peadar Coyle – Data Scientist
We will be the best place for money
BorrowersInvestors
Invests Repayments
Interest + capital Loans
World’s 1st
peer-to-peer
lending platform
in 2004
£2.5 billion
lent to date,
and our growth is
accelerating
246,000
people have taken
a Zopa loan
59,000
actively invest
through Zopa
What is PyMC3?
• Probabilistic Programming in Python
• At release stage – so ready for production
• Theano based
• Powerful sampling algorithms
• Powerful model syntax
• Recent improvements include Gaussian Processes and enhanced Variational
Inference
Some stats
• Over 6000 commits
• Over 100 contributors
Who uses it?
• Used widely in academia and industry
• https://github.com/pymc-devs/pymc3/wiki/PyMC3-Testimonials
• https://scholar.google.de/scholar?hl=en&as_sdt=0,5&sciodt=0,5&cites=6936955228135731
011&scipsc=&authuser=1&q=&scisbd=1
What is a Bayesian approach?
• The Bayesian world-view interprets probability as a measure of believability in an event, that
is, how confident are we that an event will occur.
• The Frequentist approach/ view is – considers that probability is the long-run frequency of
events.
• This doesn’t make much sense for say Presidential elections!
• Bayesians interpret a probability as a measure of beliefs. This allows us all to have different
priors.
Are Frequentist methods wrong?
• NO
• Least squares regression, LASSO regression and expectation-maximization are all powerful
and fast in many areas.
• Bayesian methods complement these techniques by solving problems that these approaches
can’t
• Or by illuminating the underlying system with more flexible modelling.
Example – Let’s look at text message data
This data comes from Cameron Davidson-Pilon from his own text message
history. He wrote the examples and the book this talk is based on. It’s cited at the
end.
Example – Inferring text message data
- A Poisson random variable is a very appropriate model for this type of count
data.
- The math will be something like C_{i} ∼ Poisson(λ)
- We don’t know what the lambda is – what is it?
Example – Inferring text message data (continued)
- It looks like the rate is higher later in the observation period.
- We’ll represent this with a ‘switchpoint’ – it’s a bit like how we write a delta
function (we use a day which we call tau)
- λ={λ1 if t<τ
- {λ2 if t≥τ
Priors – Or beliefs
- We call alpha a hyper-parameter or parent variable. In literal terms, it is a
parameter that influences other parameters.
- Alternatively, we could have two priors – one for each λi -- EXERCISE
We are interested in inferring the unknown λs. To use Bayesian inference, we need
to assign prior probabilities to the different possible values of λ What would be
good prior probability distributions for λ1 and λ2?
Recall that λ can be any positive number. As we saw earlier, the exponential
distribution provides a continuous density function for positive numbers, so it
might be a good choice for modelling λi But recall that the exponential distribution
takes a parameter of its own, so we'll need to include that parameter in our
model. Let's call that parameter α.
λ1∼Exp(α)
λ2∼Exp(α)
Priors - Continued
- We don’t care what our prior distribution (or integral) for the unknown variables
looks like.
- It’s probably intractable – so needs a method to solve.
- And we care about the posterior distribution
- What about τ?
- Due to the noisiness of the data, it’s difficult to pick out a priori where τ
might have occurred. We’ll pick a uniform prior belief to every possible
day. This is equivalent to saying
τ ∼ DiscreteUniform(1,70)
- This implies that the P(τ=k) = 1/70
The philosophy of Probabilistic Programming:
Our first hammer PyMC3
Another way of thinking about this: unlike a traditional program, which only
runs in the forward directions, a probabilistic program is run in both the
forward and backward direction. It runs forward to compute the
consequences of the assumptions it contains about the world (i.e., the model
space it represents), but it also runs backward from the data to constrain the
possible explanations. In practice, many probabilistic programming systems
will cleverly interleave these forward and backward operations to efficiently
home in on the best explanations. -- Beau Cronin – sold a Probabilistic
Programming focused company to Salesforce
Let’s specify our variables
import pymc3 as pm import theano.tensor as tt
with pm.Model() as model:
alpha = 1.0/count_data.mean() # Recall count_data is the
# variable that holds our txt counts
lambda_1 = pm.Exponential("lambda_1", alpha)
lambda_2 = pm.Exponential("lambda_2", alpha)
tau = pm.DiscreteUniform("tau", lower = 0, upper=n_count_data - 1)
Let’s create the switchpoint and add in
observations
with model:
idx = np.arange(n_count_data) # Index
lambda_ = pm.math.switch(tau >= idx, lambda_1, lambda_2)
with model:
observation = pm.Poisson("obs", lambda_, observed=count_data)
All our variables so far are random variables. We aren’t fixing any variables yet.
The variable observation combines our data (count_data), with our proposed data-
generation schema, given by the variable lambda_, through the observed keyword.
Let’s learn something
with model:
trace = pm.sample(10000, tune=5000)
We can think of the above code as a learning step. The machinery we
use is called Markov Chain Monte Carlo (MCMC), which is a whole
workshop. Let’s consider it a magic trick that helps us solve these
complicated formula.
This technique returns thousands of random variables from the
posterior distributions of λ1,λ2 and τ.
We can plot a histogram of the random variables to see what the
posterior distributions look like.
On next slide, we collect the samples (called traces in the MCMC
literature) into histograms.
The trace code
lambda_1_samples = trace['lambda_1’]
lambda_2_samples = trace['lambda_2’]
tau_samples = trace['tau']
We’ll leave out the plotting code – you can check in
the notebooks.
Posterior distributions of the variables
Interpretation
• The Bayesian methodology returns a distribution.
• We now have distributions to describe the unknown λ1,λ2 and τ
• We can see that the plausible values for the parameters are: λ1 is around 18, and λ2 is
around 23. The posterior distributions of the two lambdas are clearly distinct, indicating
that it is indeed likely that there was a change in the user’s text-message behaviour.
• Our analysis also returned a distribution τ. It’s posterior distribution is discrete. We can see
that near day 45, there was a 50% chance that the user’s behaviour changed. This confirms
that a change occurred because had no changed occurred tau would be more spread out.
We see that only a few days make any sense as potential transition points.
Why would I want to sample from the posterior?
• Entire books are devoted to explaining why.
• We’ll muse the posterior samples to answer the following question: what is expected
number of texts at day t, 0≤t≤70? Recall that the expected value of a Poisson variable is
equal to it’s parameter λ. Therefore the question is equivalent to what is the expected value
of λ at time t?
• In our code, let i index samples from the posterior distributions. Given a day t, we average
over all possible λi for the day t, using λi = λ1,i if t < τi (that is, if the behaviour change has
not yet occurred), else we use λi = λ2,i
Analysis results
- Our analysis strongly supports believing the users’ behaviour did change.
Otherwise the two lambdas would be closer in value.
- The change was sudden rather than gradual – we see this from tau’s strongly
peaked posterior distribution.
- It turns out the 45th day was Christmas and the book author was moving cities.
We introduced Bayesian Methods
Bayesian methods are about beliefs
PyMC3 allows building generative models
We get uncertainty estimates for free
We can add domain knowledge in priors
Good book resources
Online Resources
• http://docs.pymc.io/
• http://austinrochford.com/posts/2015-10-05-bayes-survival.html
• http://twiecki.github.io/
• https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-
for-Hackers

Mais conteúdo relacionado

Mais procurados

pptx - Psuedo Random Generator for Halfspaces
pptx - Psuedo Random Generator for Halfspacespptx - Psuedo Random Generator for Halfspaces
pptx - Psuedo Random Generator for Halfspaces
butest
 
Adversarial Reinforced Learning for Unsupervised Domain Adaptation
Adversarial Reinforced Learning for Unsupervised Domain AdaptationAdversarial Reinforced Learning for Unsupervised Domain Adaptation
Adversarial Reinforced Learning for Unsupervised Domain Adaptation
taeseon ryu
 

Mais procurados (20)

L1803016468
L1803016468L1803016468
L1803016468
 
I1803014852
I1803014852I1803014852
I1803014852
 
Mid term
Mid termMid term
Mid term
 
Lattice-Based Cryptography: CRYPTANALYSIS OF COMPACT-LWE
Lattice-Based Cryptography: CRYPTANALYSIS OF COMPACT-LWELattice-Based Cryptography: CRYPTANALYSIS OF COMPACT-LWE
Lattice-Based Cryptography: CRYPTANALYSIS OF COMPACT-LWE
 
Safety Verification of Deep Neural Networks_.pdf
Safety Verification of Deep Neural Networks_.pdfSafety Verification of Deep Neural Networks_.pdf
Safety Verification of Deep Neural Networks_.pdf
 
Generating sentences from a continuous space
Generating sentences from a continuous spaceGenerating sentences from a continuous space
Generating sentences from a continuous space
 
NP-Completeness - II
NP-Completeness - IINP-Completeness - II
NP-Completeness - II
 
Into to prob_prog_hari
Into to prob_prog_hariInto to prob_prog_hari
Into to prob_prog_hari
 
Homomorphic encryption and Private Machine Learning Classification
Homomorphic encryption and Private Machine Learning ClassificationHomomorphic encryption and Private Machine Learning Classification
Homomorphic encryption and Private Machine Learning Classification
 
Big o notation
Big o notationBig o notation
Big o notation
 
pptx - Psuedo Random Generator for Halfspaces
pptx - Psuedo Random Generator for Halfspacespptx - Psuedo Random Generator for Halfspaces
pptx - Psuedo Random Generator for Halfspaces
 
Template Protection with Homomorphic Encryption
Template Protection with Homomorphic EncryptionTemplate Protection with Homomorphic Encryption
Template Protection with Homomorphic Encryption
 
Profiling Java Programs for Parallelism
Profiling Java Programs for ParallelismProfiling Java Programs for Parallelism
Profiling Java Programs for Parallelism
 
International Journal of Managing Information Technology (IJMIT)
International Journal of Managing Information Technology (IJMIT)International Journal of Managing Information Technology (IJMIT)
International Journal of Managing Information Technology (IJMIT)
 
An improved spfa algorithm for single source shortest path problem using forw...
An improved spfa algorithm for single source shortest path problem using forw...An improved spfa algorithm for single source shortest path problem using forw...
An improved spfa algorithm for single source shortest path problem using forw...
 
An improved spfa algorithm for single source shortest path problem using forw...
An improved spfa algorithm for single source shortest path problem using forw...An improved spfa algorithm for single source shortest path problem using forw...
An improved spfa algorithm for single source shortest path problem using forw...
 
[Paper Reading] Attention is All You Need
[Paper Reading] Attention is All You Need[Paper Reading] Attention is All You Need
[Paper Reading] Attention is All You Need
 
Adversarial Reinforced Learning for Unsupervised Domain Adaptation
Adversarial Reinforced Learning for Unsupervised Domain AdaptationAdversarial Reinforced Learning for Unsupervised Domain Adaptation
Adversarial Reinforced Learning for Unsupervised Domain Adaptation
 
[DL輪読会]Generative Models of Visually Grounded Imagination
[DL輪読会]Generative Models of Visually Grounded Imagination[DL輪読会]Generative Models of Visually Grounded Imagination
[DL輪読会]Generative Models of Visually Grounded Imagination
 
Code Tuning
Code TuningCode Tuning
Code Tuning
 

Semelhante a Introduction to Bayesian Analysis in Python

Machine Learning
Machine LearningMachine Learning
Machine Learning
butest
 
DMDW Lesson 08 - Further Data Mining Algorithms
DMDW Lesson 08 - Further Data Mining AlgorithmsDMDW Lesson 08 - Further Data Mining Algorithms
DMDW Lesson 08 - Further Data Mining Algorithms
Johannes Hoppe
 
Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysis
chidabdu
 
Aad introduction
Aad introductionAad introduction
Aad introduction
Mr SMAK
 
Building graphs to discover information by David Martínez at Big Data Spain 2015
Building graphs to discover information by David Martínez at Big Data Spain 2015Building graphs to discover information by David Martínez at Big Data Spain 2015
Building graphs to discover information by David Martínez at Big Data Spain 2015
Big Data Spain
 

Semelhante a Introduction to Bayesian Analysis in Python (20)

Dataworkz odsc london 2018
Dataworkz odsc london 2018Dataworkz odsc london 2018
Dataworkz odsc london 2018
 
2.03.Asymptotic_analysis.pptx
2.03.Asymptotic_analysis.pptx2.03.Asymptotic_analysis.pptx
2.03.Asymptotic_analysis.pptx
 
fINAL ML PPT.pptx
fINAL ML PPT.pptxfINAL ML PPT.pptx
fINAL ML PPT.pptx
 
AI applications in education, Pascal Zoleko, Flexudy
AI applications in education, Pascal Zoleko, FlexudyAI applications in education, Pascal Zoleko, Flexudy
AI applications in education, Pascal Zoleko, Flexudy
 
Essentials of machine learning algorithms
Essentials of machine learning algorithmsEssentials of machine learning algorithms
Essentials of machine learning algorithms
 
New directions for mahout
New directions for mahoutNew directions for mahout
New directions for mahout
 
Machine Learning
Machine LearningMachine Learning
Machine Learning
 
DMDW Lesson 08 - Further Data Mining Algorithms
DMDW Lesson 08 - Further Data Mining AlgorithmsDMDW Lesson 08 - Further Data Mining Algorithms
DMDW Lesson 08 - Further Data Mining Algorithms
 
Deep learning from scratch
Deep learning from scratch Deep learning from scratch
Deep learning from scratch
 
Semantical Cognitive Scheduling
Semantical Cognitive SchedulingSemantical Cognitive Scheduling
Semantical Cognitive Scheduling
 
Neural Nets Deconstructed
Neural Nets DeconstructedNeural Nets Deconstructed
Neural Nets Deconstructed
 
working with python
working with pythonworking with python
working with python
 
Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysis
 
Aad introduction
Aad introductionAad introduction
Aad introduction
 
Jay Yagnik at AI Frontiers : A History Lesson on AI
Jay Yagnik at AI Frontiers : A History Lesson on AIJay Yagnik at AI Frontiers : A History Lesson on AI
Jay Yagnik at AI Frontiers : A History Lesson on AI
 
Introduction to machine learning
Introduction to machine learningIntroduction to machine learning
Introduction to machine learning
 
Building graphs to discover information by David Martínez at Big Data Spain 2015
Building graphs to discover information by David Martínez at Big Data Spain 2015Building graphs to discover information by David Martínez at Big Data Spain 2015
Building graphs to discover information by David Martínez at Big Data Spain 2015
 
Manifold Blurring Mean Shift algorithms for manifold denoising, report, 2012
Manifold Blurring Mean Shift algorithms for manifold denoising, report, 2012Manifold Blurring Mean Shift algorithms for manifold denoising, report, 2012
Manifold Blurring Mean Shift algorithms for manifold denoising, report, 2012
 
Computing probabilistic queries in the presence of uncertainty via probabilis...
Computing probabilistic queries in the presence of uncertainty via probabilis...Computing probabilistic queries in the presence of uncertainty via probabilis...
Computing probabilistic queries in the presence of uncertainty via probabilis...
 
Operationalizing Declarative and Procedural Knowledge
Operationalizing Declarative and Procedural KnowledgeOperationalizing Declarative and Procedural Knowledge
Operationalizing Declarative and Procedural Knowledge
 

Mais de Peadar Coyle

Mais de Peadar Coyle (8)

From Lab to Factory: Creating value with data
From Lab to Factory: Creating value with dataFrom Lab to Factory: Creating value with data
From Lab to Factory: Creating value with data
 
Consulting Skills for Data Scientists
Consulting Skills for Data ScientistsConsulting Skills for Data Scientists
Consulting Skills for Data Scientists
 
A Map of the PyData Stack
A Map of the PyData StackA Map of the PyData Stack
A Map of the PyData Stack
 
Big Data and Internet of Things for Managers
Big Data and Internet of Things for ManagersBig Data and Internet of Things for Managers
Big Data and Internet of Things for Managers
 
Introduction to Spark: Or how I learned to love 'big data' after all.
Introduction to Spark: Or how I learned to love 'big data' after all.Introduction to Spark: Or how I learned to love 'big data' after all.
Introduction to Spark: Or how I learned to love 'big data' after all.
 
Probabilistic Programming in Python
Probabilistic Programming in PythonProbabilistic Programming in Python
Probabilistic Programming in Python
 
From Lab to Factory: Or how to turn data into value
From Lab to Factory: Or how to turn data into valueFrom Lab to Factory: Or how to turn data into value
From Lab to Factory: Or how to turn data into value
 
How can Data Science benefit your business?
How can Data Science benefit your business?How can Data Science benefit your business?
How can Data Science benefit your business?
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 

Introduction to Bayesian Analysis in Python

  • 2. Peadar Coyle – Data Scientist
  • 3. We will be the best place for money
  • 4.
  • 6. World’s 1st peer-to-peer lending platform in 2004 £2.5 billion lent to date, and our growth is accelerating 246,000 people have taken a Zopa loan 59,000 actively invest through Zopa
  • 7.
  • 8.
  • 9. What is PyMC3? • Probabilistic Programming in Python • At release stage – so ready for production • Theano based • Powerful sampling algorithms • Powerful model syntax • Recent improvements include Gaussian Processes and enhanced Variational Inference
  • 10. Some stats • Over 6000 commits • Over 100 contributors
  • 11. Who uses it? • Used widely in academia and industry • https://github.com/pymc-devs/pymc3/wiki/PyMC3-Testimonials • https://scholar.google.de/scholar?hl=en&as_sdt=0,5&sciodt=0,5&cites=6936955228135731 011&scipsc=&authuser=1&q=&scisbd=1
  • 12. What is a Bayesian approach? • The Bayesian world-view interprets probability as a measure of believability in an event, that is, how confident are we that an event will occur. • The Frequentist approach/ view is – considers that probability is the long-run frequency of events. • This doesn’t make much sense for say Presidential elections! • Bayesians interpret a probability as a measure of beliefs. This allows us all to have different priors.
  • 13. Are Frequentist methods wrong? • NO • Least squares regression, LASSO regression and expectation-maximization are all powerful and fast in many areas. • Bayesian methods complement these techniques by solving problems that these approaches can’t • Or by illuminating the underlying system with more flexible modelling.
  • 14. Example – Let’s look at text message data This data comes from Cameron Davidson-Pilon from his own text message history. He wrote the examples and the book this talk is based on. It’s cited at the end.
  • 15. Example – Inferring text message data - A Poisson random variable is a very appropriate model for this type of count data. - The math will be something like C_{i} ∼ Poisson(λ) - We don’t know what the lambda is – what is it?
  • 16. Example – Inferring text message data (continued) - It looks like the rate is higher later in the observation period. - We’ll represent this with a ‘switchpoint’ – it’s a bit like how we write a delta function (we use a day which we call tau) - λ={λ1 if t<τ - {λ2 if t≥τ
  • 17. Priors – Or beliefs - We call alpha a hyper-parameter or parent variable. In literal terms, it is a parameter that influences other parameters. - Alternatively, we could have two priors – one for each λi -- EXERCISE We are interested in inferring the unknown λs. To use Bayesian inference, we need to assign prior probabilities to the different possible values of λ What would be good prior probability distributions for λ1 and λ2? Recall that λ can be any positive number. As we saw earlier, the exponential distribution provides a continuous density function for positive numbers, so it might be a good choice for modelling λi But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter α. λ1∼Exp(α) λ2∼Exp(α)
  • 18. Priors - Continued - We don’t care what our prior distribution (or integral) for the unknown variables looks like. - It’s probably intractable – so needs a method to solve. - And we care about the posterior distribution - What about τ? - Due to the noisiness of the data, it’s difficult to pick out a priori where τ might have occurred. We’ll pick a uniform prior belief to every possible day. This is equivalent to saying τ ∼ DiscreteUniform(1,70) - This implies that the P(τ=k) = 1/70
  • 19. The philosophy of Probabilistic Programming: Our first hammer PyMC3 Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations. -- Beau Cronin – sold a Probabilistic Programming focused company to Salesforce
  • 20. Let’s specify our variables import pymc3 as pm import theano.tensor as tt with pm.Model() as model: alpha = 1.0/count_data.mean() # Recall count_data is the # variable that holds our txt counts lambda_1 = pm.Exponential("lambda_1", alpha) lambda_2 = pm.Exponential("lambda_2", alpha) tau = pm.DiscreteUniform("tau", lower = 0, upper=n_count_data - 1)
  • 21. Let’s create the switchpoint and add in observations with model: idx = np.arange(n_count_data) # Index lambda_ = pm.math.switch(tau >= idx, lambda_1, lambda_2) with model: observation = pm.Poisson("obs", lambda_, observed=count_data) All our variables so far are random variables. We aren’t fixing any variables yet. The variable observation combines our data (count_data), with our proposed data- generation schema, given by the variable lambda_, through the observed keyword.
  • 22. Let’s learn something with model: trace = pm.sample(10000, tune=5000) We can think of the above code as a learning step. The machinery we use is called Markov Chain Monte Carlo (MCMC), which is a whole workshop. Let’s consider it a magic trick that helps us solve these complicated formula. This technique returns thousands of random variables from the posterior distributions of λ1,λ2 and τ. We can plot a histogram of the random variables to see what the posterior distributions look like. On next slide, we collect the samples (called traces in the MCMC literature) into histograms.
  • 23. The trace code lambda_1_samples = trace['lambda_1’] lambda_2_samples = trace['lambda_2’] tau_samples = trace['tau'] We’ll leave out the plotting code – you can check in the notebooks.
  • 24. Posterior distributions of the variables
  • 25. Interpretation • The Bayesian methodology returns a distribution. • We now have distributions to describe the unknown λ1,λ2 and τ • We can see that the plausible values for the parameters are: λ1 is around 18, and λ2 is around 23. The posterior distributions of the two lambdas are clearly distinct, indicating that it is indeed likely that there was a change in the user’s text-message behaviour. • Our analysis also returned a distribution τ. It’s posterior distribution is discrete. We can see that near day 45, there was a 50% chance that the user’s behaviour changed. This confirms that a change occurred because had no changed occurred tau would be more spread out. We see that only a few days make any sense as potential transition points.
  • 26. Why would I want to sample from the posterior? • Entire books are devoted to explaining why. • We’ll muse the posterior samples to answer the following question: what is expected number of texts at day t, 0≤t≤70? Recall that the expected value of a Poisson variable is equal to it’s parameter λ. Therefore the question is equivalent to what is the expected value of λ at time t? • In our code, let i index samples from the posterior distributions. Given a day t, we average over all possible λi for the day t, using λi = λ1,i if t < τi (that is, if the behaviour change has not yet occurred), else we use λi = λ2,i
  • 27. Analysis results - Our analysis strongly supports believing the users’ behaviour did change. Otherwise the two lambdas would be closer in value. - The change was sudden rather than gradual – we see this from tau’s strongly peaked posterior distribution. - It turns out the 45th day was Christmas and the book author was moving cities.
  • 28. We introduced Bayesian Methods Bayesian methods are about beliefs PyMC3 allows building generative models We get uncertainty estimates for free We can add domain knowledge in priors
  • 30. Online Resources • http://docs.pymc.io/ • http://austinrochford.com/posts/2015-10-05-bayes-survival.html • http://twiecki.github.io/ • https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods- for-Hackers