Skip to content

Instantly share code, notes, and snippets.

@tleysh
Last active September 8, 2021 19:30
Show Gist options
  • Save tleysh/3315e42be589d8fc340d5ae71440b771 to your computer and use it in GitHub Desktop.
Save tleysh/3315e42be589d8fc340d5ae71440b771 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#Distance function - Absolute difference \n",
"def distance_function(X,Y):\n",
" distance = (1/len(X))*abs(sum(X)-sum(Y))\n",
" return distance\n",
"\n",
"#The ABC method with uniform prior, returns samples from the posterior\n",
"def ABC_Method_Uniform_Prior(Observed_data,Number_of_Samples,threshold):\n",
" #The observed data \n",
" #initialise Posterior array\n",
" Posterior_distribution = []\n",
" #trials\n",
" n = len(Observed_data) \n",
" #loop through to get the samples. \n",
" for i in range(0,Number_of_Samples):\n",
" distance = threshold+1\n",
" #While the distance is greater than the threshold continue to sample theta from the beta distribution\n",
" while distance > threshold:\n",
" #sample theta from the prior\n",
" theta = np.random.beta(1, 1, size=1)[0]\n",
" # generate the sim data \n",
" X = np.random.binomial(1, theta, n)\n",
" # calcalute the distance from Y \n",
" distance = distance_function(X,Observed_data)\n",
" Posterior_distribution.append(theta)\n",
" return Posterior_distribution"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment