{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Bayesian Methods\n",
"### [Neil D. Lawrence](http://inverseprobability.com), Amazon Cambridge and University of Sheffield\n",
"### 2018-11-14\n",
"\n",
"**Abstract**: In this session we review the *probabilistic* approach to machine\n",
"learning. We start with a review of probability, and introduce the\n",
"concepts of probabilistic modelling. We then apply the approach in\n",
"practice to Naive Bayesian classification. In this session we review the\n",
"probabilistic formulation of a classification model, reviewing initially\n",
"maximum likelihood and the naive Bayes model.\n",
"\n",
"$$\n",
"\\newcommand{\\tk}[1]{}\n",
"%\\newcommand{\\tk}[1]{\\textbf{TK}: #1}\n",
"\\newcommand{\\Amatrix}{\\mathbf{A}}\n",
"\\newcommand{\\KL}[2]{\\text{KL}\\left( #1\\,\\|\\,#2 \\right)}\n",
"\\newcommand{\\Kaast}{\\kernelMatrix_{\\mathbf{ \\ast}\\mathbf{ \\ast}}}\n",
"\\newcommand{\\Kastu}{\\kernelMatrix_{\\mathbf{ \\ast} \\inducingVector}}\n",
"\\newcommand{\\Kff}{\\kernelMatrix_{\\mappingFunctionVector \\mappingFunctionVector}}\n",
"\\newcommand{\\Kfu}{\\kernelMatrix_{\\mappingFunctionVector \\inducingVector}}\n",
"\\newcommand{\\Kuast}{\\kernelMatrix_{\\inducingVector \\bf\\ast}}\n",
"\\newcommand{\\Kuf}{\\kernelMatrix_{\\inducingVector \\mappingFunctionVector}}\n",
"\\newcommand{\\Kuu}{\\kernelMatrix_{\\inducingVector \\inducingVector}}\n",
"\\newcommand{\\Kuui}{\\Kuu^{-1}}\n",
"\\newcommand{\\Qaast}{\\mathbf{Q}_{\\bf \\ast \\ast}}\n",
"\\newcommand{\\Qastf}{\\mathbf{Q}_{\\ast \\mappingFunction}}\n",
"\\newcommand{\\Qfast}{\\mathbf{Q}_{\\mappingFunctionVector \\bf \\ast}}\n",
"\\newcommand{\\Qff}{\\mathbf{Q}_{\\mappingFunctionVector \\mappingFunctionVector}}\n",
"\\newcommand{\\aMatrix}{\\mathbf{A}}\n",
"\\newcommand{\\aScalar}{a}\n",
"\\newcommand{\\aVector}{\\mathbf{a}}\n",
"\\newcommand{\\acceleration}{a}\n",
"\\newcommand{\\bMatrix}{\\mathbf{B}}\n",
"\\newcommand{\\bScalar}{b}\n",
"\\newcommand{\\bVector}{\\mathbf{b}}\n",
"\\newcommand{\\basisFunc}{\\phi}\n",
"\\newcommand{\\basisFuncVector}{\\boldsymbol{ \\basisFunc}}\n",
"\\newcommand{\\basisFunction}{\\phi}\n",
"\\newcommand{\\basisLocation}{\\mu}\n",
"\\newcommand{\\basisMatrix}{\\boldsymbol{ \\Phi}}\n",
"\\newcommand{\\basisScalar}{\\basisFunction}\n",
"\\newcommand{\\basisVector}{\\boldsymbol{ \\basisFunction}}\n",
"\\newcommand{\\activationFunction}{\\phi}\n",
"\\newcommand{\\activationMatrix}{\\boldsymbol{ \\Phi}}\n",
"\\newcommand{\\activationScalar}{\\basisFunction}\n",
"\\newcommand{\\activationVector}{\\boldsymbol{ \\basisFunction}}\n",
"\\newcommand{\\bigO}{\\mathcal{O}}\n",
"\\newcommand{\\binomProb}{\\pi}\n",
"\\newcommand{\\cMatrix}{\\mathbf{C}}\n",
"\\newcommand{\\cbasisMatrix}{\\hat{\\boldsymbol{ \\Phi}}}\n",
"\\newcommand{\\cdataMatrix}{\\hat{\\dataMatrix}}\n",
"\\newcommand{\\cdataScalar}{\\hat{\\dataScalar}}\n",
"\\newcommand{\\cdataVector}{\\hat{\\dataVector}}\n",
"\\newcommand{\\centeredKernelMatrix}{\\mathbf{ \\MakeUppercase{\\centeredKernelScalar}}}\n",
"\\newcommand{\\centeredKernelScalar}{b}\n",
"\\newcommand{\\centeredKernelVector}{\\centeredKernelScalar}\n",
"\\newcommand{\\centeringMatrix}{\\mathbf{H}}\n",
"\\newcommand{\\chiSquaredDist}[2]{\\chi_{#1}^{2}\\left(#2\\right)}\n",
"\\newcommand{\\chiSquaredSamp}[1]{\\chi_{#1}^{2}}\n",
"\\newcommand{\\conditionalCovariance}{\\boldsymbol{ \\Sigma}}\n",
"\\newcommand{\\coregionalizationMatrix}{\\mathbf{B}}\n",
"\\newcommand{\\coregionalizationScalar}{b}\n",
"\\newcommand{\\coregionalizationVector}{\\mathbf{ \\coregionalizationScalar}}\n",
"\\newcommand{\\covDist}[2]{\\text{cov}_{#2}\\left(#1\\right)}\n",
"\\newcommand{\\covSamp}[1]{\\text{cov}\\left(#1\\right)}\n",
"\\newcommand{\\covarianceScalar}{c}\n",
"\\newcommand{\\covarianceVector}{\\mathbf{ \\covarianceScalar}}\n",
"\\newcommand{\\covarianceMatrix}{\\mathbf{C}}\n",
"\\newcommand{\\covarianceMatrixTwo}{\\boldsymbol{ \\Sigma}}\n",
"\\newcommand{\\croupierScalar}{s}\n",
"\\newcommand{\\croupierVector}{\\mathbf{ \\croupierScalar}}\n",
"\\newcommand{\\croupierMatrix}{\\mathbf{ \\MakeUppercase{\\croupierScalar}}}\n",
"\\newcommand{\\dataDim}{p}\n",
"\\newcommand{\\dataIndex}{i}\n",
"\\newcommand{\\dataIndexTwo}{j}\n",
"\\newcommand{\\dataMatrix}{\\mathbf{Y}}\n",
"\\newcommand{\\dataScalar}{y}\n",
"\\newcommand{\\dataSet}{\\mathcal{D}}\n",
"\\newcommand{\\dataStd}{\\sigma}\n",
"\\newcommand{\\dataVector}{\\mathbf{ \\dataScalar}}\n",
"\\newcommand{\\decayRate}{d}\n",
"\\newcommand{\\degreeMatrix}{\\mathbf{ \\MakeUppercase{\\degreeScalar}}}\n",
"\\newcommand{\\degreeScalar}{d}\n",
"\\newcommand{\\degreeVector}{\\mathbf{ \\degreeScalar}}\n",
"% Already defined by latex\n",
"%\\newcommand{\\det}[1]{\\left|#1\\right|}\n",
"\\newcommand{\\diag}[1]{\\text{diag}\\left(#1\\right)}\n",
"\\newcommand{\\diagonalMatrix}{\\mathbf{D}}\n",
"\\newcommand{\\diff}[2]{\\frac{\\text{d}#1}{\\text{d}#2}}\n",
"\\newcommand{\\diffTwo}[2]{\\frac{\\text{d}^2#1}{\\text{d}#2^2}}\n",
"\\newcommand{\\displacement}{x}\n",
"\\newcommand{\\displacementVector}{\\textbf{\\displacement}}\n",
"\\newcommand{\\distanceMatrix}{\\mathbf{ \\MakeUppercase{\\distanceScalar}}}\n",
"\\newcommand{\\distanceScalar}{d}\n",
"\\newcommand{\\distanceVector}{\\mathbf{ \\distanceScalar}}\n",
"\\newcommand{\\eigenvaltwo}{\\ell}\n",
"\\newcommand{\\eigenvaltwoMatrix}{\\mathbf{L}}\n",
"\\newcommand{\\eigenvaltwoVector}{\\mathbf{l}}\n",
"\\newcommand{\\eigenvalue}{\\lambda}\n",
"\\newcommand{\\eigenvalueMatrix}{\\boldsymbol{ \\Lambda}}\n",
"\\newcommand{\\eigenvalueVector}{\\boldsymbol{ \\lambda}}\n",
"\\newcommand{\\eigenvector}{\\mathbf{ \\eigenvectorScalar}}\n",
"\\newcommand{\\eigenvectorMatrix}{\\mathbf{U}}\n",
"\\newcommand{\\eigenvectorScalar}{u}\n",
"\\newcommand{\\eigenvectwo}{\\mathbf{v}}\n",
"\\newcommand{\\eigenvectwoMatrix}{\\mathbf{V}}\n",
"\\newcommand{\\eigenvectwoScalar}{v}\n",
"\\newcommand{\\entropy}[1]{\\mathcal{H}\\left(#1\\right)}\n",
"\\newcommand{\\errorFunction}{E}\n",
"\\newcommand{\\expDist}[2]{\\left<#1\\right>_{#2}}\n",
"\\newcommand{\\expSamp}[1]{\\left<#1\\right>}\n",
"\\newcommand{\\expectation}[1]{\\left\\langle #1 \\right\\rangle }\n",
"\\newcommand{\\expectationDist}[2]{\\left\\langle #1 \\right\\rangle _{#2}}\n",
"\\newcommand{\\expectedDistanceMatrix}{\\mathcal{D}}\n",
"\\newcommand{\\eye}{\\mathbf{I}}\n",
"\\newcommand{\\fantasyDim}{r}\n",
"\\newcommand{\\fantasyMatrix}{\\mathbf{ \\MakeUppercase{\\fantasyScalar}}}\n",
"\\newcommand{\\fantasyScalar}{z}\n",
"\\newcommand{\\fantasyVector}{\\mathbf{ \\fantasyScalar}}\n",
"\\newcommand{\\featureStd}{\\varsigma}\n",
"\\newcommand{\\gammaCdf}[3]{\\mathcal{GAMMA CDF}\\left(#1|#2,#3\\right)}\n",
"\\newcommand{\\gammaDist}[3]{\\mathcal{G}\\left(#1|#2,#3\\right)}\n",
"\\newcommand{\\gammaSamp}[2]{\\mathcal{G}\\left(#1,#2\\right)}\n",
"\\newcommand{\\gaussianDist}[3]{\\mathcal{N}\\left(#1|#2,#3\\right)}\n",
"\\newcommand{\\gaussianSamp}[2]{\\mathcal{N}\\left(#1,#2\\right)}\n",
"\\newcommand{\\given}{|}\n",
"\\newcommand{\\half}{\\frac{1}{2}}\n",
"\\newcommand{\\heaviside}{H}\n",
"\\newcommand{\\hiddenMatrix}{\\mathbf{ \\MakeUppercase{\\hiddenScalar}}}\n",
"\\newcommand{\\hiddenScalar}{h}\n",
"\\newcommand{\\hiddenVector}{\\mathbf{ \\hiddenScalar}}\n",
"\\newcommand{\\identityMatrix}{\\eye}\n",
"\\newcommand{\\inducingInputScalar}{z}\n",
"\\newcommand{\\inducingInputVector}{\\mathbf{ \\inducingInputScalar}}\n",
"\\newcommand{\\inducingInputMatrix}{\\mathbf{Z}}\n",
"\\newcommand{\\inducingScalar}{u}\n",
"\\newcommand{\\inducingVector}{\\mathbf{ \\inducingScalar}}\n",
"\\newcommand{\\inducingMatrix}{\\mathbf{U}}\n",
"\\newcommand{\\inlineDiff}[2]{\\text{d}#1/\\text{d}#2}\n",
"\\newcommand{\\inputDim}{q}\n",
"\\newcommand{\\inputMatrix}{\\mathbf{X}}\n",
"\\newcommand{\\inputScalar}{x}\n",
"\\newcommand{\\inputSpace}{\\mathcal{X}}\n",
"\\newcommand{\\inputVals}{\\inputVector}\n",
"\\newcommand{\\inputVector}{\\mathbf{ \\inputScalar}}\n",
"\\newcommand{\\iterNum}{k}\n",
"\\newcommand{\\kernel}{\\kernelScalar}\n",
"\\newcommand{\\kernelMatrix}{\\mathbf{K}}\n",
"\\newcommand{\\kernelScalar}{k}\n",
"\\newcommand{\\kernelVector}{\\mathbf{ \\kernelScalar}}\n",
"\\newcommand{\\kff}{\\kernelScalar_{\\mappingFunction \\mappingFunction}}\n",
"\\newcommand{\\kfu}{\\kernelVector_{\\mappingFunction \\inducingScalar}}\n",
"\\newcommand{\\kuf}{\\kernelVector_{\\inducingScalar \\mappingFunction}}\n",
"\\newcommand{\\kuu}{\\kernelVector_{\\inducingScalar \\inducingScalar}}\n",
"\\newcommand{\\lagrangeMultiplier}{\\lambda}\n",
"\\newcommand{\\lagrangeMultiplierMatrix}{\\boldsymbol{ \\Lambda}}\n",
"\\newcommand{\\lagrangian}{L}\n",
"\\newcommand{\\laplacianFactor}{\\mathbf{ \\MakeUppercase{\\laplacianFactorScalar}}}\n",
"\\newcommand{\\laplacianFactorScalar}{m}\n",
"\\newcommand{\\laplacianFactorVector}{\\mathbf{ \\laplacianFactorScalar}}\n",
"\\newcommand{\\laplacianMatrix}{\\mathbf{L}}\n",
"\\newcommand{\\laplacianScalar}{\\ell}\n",
"\\newcommand{\\laplacianVector}{\\mathbf{ \\ell}}\n",
"\\newcommand{\\latentDim}{q}\n",
"\\newcommand{\\latentDistanceMatrix}{\\boldsymbol{ \\Delta}}\n",
"\\newcommand{\\latentDistanceScalar}{\\delta}\n",
"\\newcommand{\\latentDistanceVector}{\\boldsymbol{ \\delta}}\n",
"\\newcommand{\\latentForce}{f}\n",
"\\newcommand{\\latentFunction}{u}\n",
"\\newcommand{\\latentFunctionVector}{\\mathbf{ \\latentFunction}}\n",
"\\newcommand{\\latentFunctionMatrix}{\\mathbf{ \\MakeUppercase{\\latentFunction}}}\n",
"\\newcommand{\\latentIndex}{j}\n",
"\\newcommand{\\latentScalar}{z}\n",
"\\newcommand{\\latentVector}{\\mathbf{ \\latentScalar}}\n",
"\\newcommand{\\latentMatrix}{\\mathbf{Z}}\n",
"\\newcommand{\\learnRate}{\\eta}\n",
"\\newcommand{\\lengthScale}{\\ell}\n",
"\\newcommand{\\rbfWidth}{\\ell}\n",
"\\newcommand{\\likelihoodBound}{\\mathcal{L}}\n",
"\\newcommand{\\likelihoodFunction}{L}\n",
"\\newcommand{\\locationScalar}{\\mu}\n",
"\\newcommand{\\locationVector}{\\boldsymbol{ \\locationScalar}}\n",
"\\newcommand{\\locationMatrix}{\\mathbf{M}}\n",
"\\newcommand{\\variance}[1]{\\text{var}\\left( #1 \\right)}\n",
"\\newcommand{\\mappingFunction}{f}\n",
"\\newcommand{\\mappingFunctionMatrix}{\\mathbf{F}}\n",
"\\newcommand{\\mappingFunctionTwo}{g}\n",
"\\newcommand{\\mappingFunctionTwoMatrix}{\\mathbf{G}}\n",
"\\newcommand{\\mappingFunctionTwoVector}{\\mathbf{ \\mappingFunctionTwo}}\n",
"\\newcommand{\\mappingFunctionVector}{\\mathbf{ \\mappingFunction}}\n",
"\\newcommand{\\scaleScalar}{s}\n",
"\\newcommand{\\mappingScalar}{w}\n",
"\\newcommand{\\mappingVector}{\\mathbf{ \\mappingScalar}}\n",
"\\newcommand{\\mappingMatrix}{\\mathbf{W}}\n",
"\\newcommand{\\mappingScalarTwo}{v}\n",
"\\newcommand{\\mappingVectorTwo}{\\mathbf{ \\mappingScalarTwo}}\n",
"\\newcommand{\\mappingMatrixTwo}{\\mathbf{V}}\n",
"\\newcommand{\\maxIters}{K}\n",
"\\newcommand{\\meanMatrix}{\\mathbf{M}}\n",
"\\newcommand{\\meanScalar}{\\mu}\n",
"\\newcommand{\\meanTwoMatrix}{\\mathbf{M}}\n",
"\\newcommand{\\meanTwoScalar}{m}\n",
"\\newcommand{\\meanTwoVector}{\\mathbf{ \\meanTwoScalar}}\n",
"\\newcommand{\\meanVector}{\\boldsymbol{ \\meanScalar}}\n",
"\\newcommand{\\mrnaConcentration}{m}\n",
"\\newcommand{\\naturalFrequency}{\\omega}\n",
"\\newcommand{\\neighborhood}[1]{\\mathcal{N}\\left( #1 \\right)}\n",
"\\newcommand{\\neilurl}{http://inverseprobability.com/}\n",
"\\newcommand{\\noiseMatrix}{\\boldsymbol{ E}}\n",
"\\newcommand{\\noiseScalar}{\\epsilon}\n",
"\\newcommand{\\noiseVector}{\\boldsymbol{ \\epsilon}}\n",
"\\newcommand{\\norm}[1]{\\left\\Vert #1 \\right\\Vert}\n",
"\\newcommand{\\normalizedLaplacianMatrix}{\\hat{\\mathbf{L}}}\n",
"\\newcommand{\\normalizedLaplacianScalar}{\\hat{\\ell}}\n",
"\\newcommand{\\normalizedLaplacianVector}{\\hat{\\mathbf{ \\ell}}}\n",
"\\newcommand{\\numActive}{m}\n",
"\\newcommand{\\numBasisFunc}{m}\n",
"\\newcommand{\\numComponents}{m}\n",
"\\newcommand{\\numComps}{K}\n",
"\\newcommand{\\numData}{n}\n",
"\\newcommand{\\numFeatures}{K}\n",
"\\newcommand{\\numHidden}{h}\n",
"\\newcommand{\\numInducing}{m}\n",
"\\newcommand{\\numLayers}{\\ell}\n",
"\\newcommand{\\numNeighbors}{K}\n",
"\\newcommand{\\numSequences}{s}\n",
"\\newcommand{\\numSuccess}{s}\n",
"\\newcommand{\\numTasks}{m}\n",
"\\newcommand{\\numTime}{T}\n",
"\\newcommand{\\numTrials}{S}\n",
"\\newcommand{\\outputIndex}{j}\n",
"\\newcommand{\\paramVector}{\\boldsymbol{ \\theta}}\n",
"\\newcommand{\\parameterMatrix}{\\boldsymbol{ \\Theta}}\n",
"\\newcommand{\\parameterScalar}{\\theta}\n",
"\\newcommand{\\parameterVector}{\\boldsymbol{ \\parameterScalar}}\n",
"\\newcommand{\\partDiff}[2]{\\frac{\\partial#1}{\\partial#2}}\n",
"\\newcommand{\\precisionScalar}{j}\n",
"\\newcommand{\\precisionVector}{\\mathbf{ \\precisionScalar}}\n",
"\\newcommand{\\precisionMatrix}{\\mathbf{J}}\n",
"\\newcommand{\\pseudotargetScalar}{\\widetilde{y}}\n",
"\\newcommand{\\pseudotargetVector}{\\mathbf{ \\pseudotargetScalar}}\n",
"\\newcommand{\\pseudotargetMatrix}{\\mathbf{ \\widetilde{Y}}}\n",
"\\newcommand{\\rank}[1]{\\text{rank}\\left(#1\\right)}\n",
"\\newcommand{\\rayleighDist}[2]{\\mathcal{R}\\left(#1|#2\\right)}\n",
"\\newcommand{\\rayleighSamp}[1]{\\mathcal{R}\\left(#1\\right)}\n",
"\\newcommand{\\responsibility}{r}\n",
"\\newcommand{\\rotationScalar}{r}\n",
"\\newcommand{\\rotationVector}{\\mathbf{ \\rotationScalar}}\n",
"\\newcommand{\\rotationMatrix}{\\mathbf{R}}\n",
"\\newcommand{\\sampleCovScalar}{s}\n",
"\\newcommand{\\sampleCovVector}{\\mathbf{ \\sampleCovScalar}}\n",
"\\newcommand{\\sampleCovMatrix}{\\mathbf{s}}\n",
"\\newcommand{\\scalarProduct}[2]{\\left\\langle{#1},{#2}\\right\\rangle}\n",
"\\newcommand{\\sign}[1]{\\text{sign}\\left(#1\\right)}\n",
"\\newcommand{\\sigmoid}[1]{\\sigma\\left(#1\\right)}\n",
"\\newcommand{\\singularvalue}{\\ell}\n",
"\\newcommand{\\singularvalueMatrix}{\\mathbf{L}}\n",
"\\newcommand{\\singularvalueVector}{\\mathbf{l}}\n",
"\\newcommand{\\sorth}{\\mathbf{u}}\n",
"\\newcommand{\\spar}{\\lambda}\n",
"\\newcommand{\\trace}[1]{\\text{tr}\\left(#1\\right)}\n",
"\\newcommand{\\BasalRate}{B}\n",
"\\newcommand{\\DampingCoefficient}{C}\n",
"\\newcommand{\\DecayRate}{D}\n",
"\\newcommand{\\Displacement}{X}\n",
"\\newcommand{\\LatentForce}{F}\n",
"\\newcommand{\\Mass}{M}\n",
"\\newcommand{\\Sensitivity}{S}\n",
"\\newcommand{\\basalRate}{b}\n",
"\\newcommand{\\dampingCoefficient}{c}\n",
"\\newcommand{\\mass}{m}\n",
"\\newcommand{\\sensitivity}{s}\n",
"\\newcommand{\\springScalar}{\\kappa}\n",
"\\newcommand{\\springVector}{\\boldsymbol{ \\kappa}}\n",
"\\newcommand{\\springMatrix}{\\boldsymbol{ \\mathcal{K}}}\n",
"\\newcommand{\\tfConcentration}{p}\n",
"\\newcommand{\\tfDecayRate}{\\delta}\n",
"\\newcommand{\\tfMrnaConcentration}{f}\n",
"\\newcommand{\\tfVector}{\\mathbf{ \\tfConcentration}}\n",
"\\newcommand{\\velocity}{v}\n",
"\\newcommand{\\sufficientStatsScalar}{g}\n",
"\\newcommand{\\sufficientStatsVector}{\\mathbf{ \\sufficientStatsScalar}}\n",
"\\newcommand{\\sufficientStatsMatrix}{\\mathbf{G}}\n",
"\\newcommand{\\switchScalar}{s}\n",
"\\newcommand{\\switchVector}{\\mathbf{ \\switchScalar}}\n",
"\\newcommand{\\switchMatrix}{\\mathbf{S}}\n",
"\\newcommand{\\tr}[1]{\\text{tr}\\left(#1\\right)}\n",
"\\newcommand{\\loneNorm}[1]{\\left\\Vert #1 \\right\\Vert_1}\n",
"\\newcommand{\\ltwoNorm}[1]{\\left\\Vert #1 \\right\\Vert_2}\n",
"\\newcommand{\\onenorm}[1]{\\left\\vert#1\\right\\vert_1}\n",
"\\newcommand{\\twonorm}[1]{\\left\\Vert #1 \\right\\Vert}\n",
"\\newcommand{\\vScalar}{v}\n",
"\\newcommand{\\vVector}{\\mathbf{v}}\n",
"\\newcommand{\\vMatrix}{\\mathbf{V}}\n",
"\\newcommand{\\varianceDist}[2]{\\text{var}_{#2}\\left( #1 \\right)}\n",
"% Already defined by latex\n",
"%\\newcommand{\\vec}{#1:}\n",
"\\newcommand{\\vecb}[1]{\\left(#1\\right):}\n",
"\\newcommand{\\weightScalar}{w}\n",
"\\newcommand{\\weightVector}{\\mathbf{ \\weightScalar}}\n",
"\\newcommand{\\weightMatrix}{\\mathbf{W}}\n",
"\\newcommand{\\weightedAdjacencyMatrix}{\\mathbf{A}}\n",
"\\newcommand{\\weightedAdjacencyScalar}{a}\n",
"\\newcommand{\\weightedAdjacencyVector}{\\mathbf{ \\weightedAdjacencyScalar}}\n",
"\\newcommand{\\onesVector}{\\mathbf{1}}\n",
"\\newcommand{\\zerosVector}{\\mathbf{0}}\n",
"$$\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"# What is Machine Learning? \\[edit\\]\n",
"\n",
"What is machine learning? At its most basic level machine learning is a\n",
"combination of\n",
"\n",
"$$\\text{data} + \\text{model} \\xrightarrow{\\text{compute}} \\text{prediction}$$\n",
"\n",
"where *data* is our observations. They can be actively or passively\n",
"acquired (meta-data). The *model* contains our assumptions, based on\n",
"previous experience. That experience can be other data, it can come from\n",
"transfer learning, or it can merely be our beliefs about the\n",
"regularities of the universe. In humans our models include our inductive\n",
"biases. The *prediction* is an action to be taken or a categorization or\n",
"a quality score. The reason that machine learning has become a mainstay\n",
"of artificial intelligence is the importance of predictions in\n",
"artificial intelligence. The data and the model are combined through\n",
"computation.\n",
"\n",
"In practice we normally perform machine learning using two functions. To\n",
"combine data with a model we typically make use of:\n",
"\n",
"**a prediction function** a function which is used to make the\n",
"predictions. It includes our beliefs about the regularities of the\n",
"universe, our assumptions about how the world works, e.g. smoothness,\n",
"spatial similarities, temporal similarities.\n",
"\n",
"**an objective function** a function which defines the cost of\n",
"misprediction. Typically it includes knowledge about the world's\n",
"generating processes (probabilistic objectives) or the costs we pay for\n",
"mispredictions (empiricial risk minimization).\n",
"\n",
"The combination of data and model through the prediction function and\n",
"the objectie function leads to a *learning algorithm*. The class of\n",
"prediction functions and objective functions we can make use of is\n",
"restricted by the algorithms they lead to. If the prediction function or\n",
"the objective function are too complex, then it can be difficult to find\n",
"an appropriate learning algorithm. Much of the acdemic field of machine\n",
"learning is the quest for new learning algorithms that allow us to bring\n",
"different types of models and data together.\n",
"\n",
"A useful reference for state of the art in machine learning is the UK\n",
"Royal Society Report, [Machine Learning: Power and Promise of Computers\n",
"that Learn by\n",
"Example](https://royalsociety.org/~/media/policy/projects/machine-learning/publications/machine-learning-report.pdf).\n",
"\n",
"You can also check my post blog post on [What is Machine\n",
"Learning?](http://inverseprobability.com/2017/07/17/what-is-machine-learning)..\n",
"\n",
"# Nigerian NMIS Data \\[edit\\]\n",
"\n",
"As an example data set we will use Nigerian NMIS Health Facility data\n",
"from openAFRICA. It can be found here\n",
"\n",
"\n",
"Taking from the information on the site,\n",
"\n",
"> The Nigeria MDG (Millennium Development Goals) Information System --\n",
"> NMIS health facility data is collected by the Office of the Senior\n",
"> Special Assistant to the President on the Millennium Development Goals\n",
"> (OSSAP-MDGs) in partner with the Sustainable Engineering Lab at\n",
"> Columbia University. A rigorous, geo-referenced baseline facility\n",
"> inventory across Nigeria is created spanning from 2009 to 2011 with an\n",
"> additional survey effort to increase coverage in 2014, to build\n",
"> Nigeria's first nation-wide inventory of health facility. The database\n",
"> includes 34,139 health facilities info in Nigeria.\n",
">\n",
"> The goal of this database is to make the data collected available to\n",
"> planners, government officials, and the public, to be used to make\n",
"> strategic decisions for planning relevant interventions.\n",
">\n",
"> For data inquiry, please contact Ms. Funlola Osinupebi, Performance\n",
"> Monitoring & Communications, Advisory Power Team, Office of the Vice\n",
"> President at funlola.osinupebi\\@aptovp.org\n",
">\n",
"> To learn more, please visit\n",
"> \n",
">\n",
"> Suggested citation: Nigeria NMIS facility database (2014), the Office\n",
"> of the Senior Special Assistant to the President on the Millennium\n",
"> Development Goals (OSSAP-MDGs) & Columbia University"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import urllib.request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"urllib.request.urlretrieve('https://energydata.info/dataset/f85d1796-e7f2-4630-be84-79420174e3bd/resource/6e640a13-cab4-457b-b9e6-0336051bac27/download/healthmopupandbaselinenmisfacility.csv', 'healthmopupandbaselinenmisfacility.csv')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data = pd.read_csv('healthmopupandbaselinenmisfacility.csv')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Once it is loaded in the data can be summarized using the `describe`\n",
"method in pandas."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data.describe()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In python and jupyter notebook it is possible to see a list of all\n",
"possible functions and attributes by typing the name of the object\n",
"followed by `.` for example in the above case if we type\n",
"`data.` it show the columns available (these are attributes in\n",
"pandas dataframes) such as `num_nurses_fulltime`, and also functions,\n",
"such as `.describe()`.\n",
"\n",
"For functions we can also see the documentation about the function by\n",
"following the name with a question mark. This will open a box with\n",
"documentation at the bottom which can be closed with the x button."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data.describe?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The NMIS facility data is stored in an object known as a 'data frame'.\n",
"Data frames come from the statistical family of programming languages\n",
"based on `S`, the most widely used of which is\n",
"[`R`](http://en.wikipedia.org/wiki/R_(programming_language)). The data\n",
"frame gives us a convenient object for manipulating data. The describe\n",
"method summarizes which columns there are in the data frame and gives us\n",
"counts, means, standard deviations and percentiles for the values in\n",
"those columns. To access a column directly we can write"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(data['num_doctors_fulltime'])\n",
"#print(data['num_nurses_fulltime'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This shows the number of doctors per facility, number of nurses and\n",
"number of community health workers (CHEWS). We can plot the number of\n",
"doctors against the number of nurses as follows."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# this ensures the plot appears in the web browser\n",
"%matplotlib inline \n",
"import matplotlib.pyplot as plt # this imports the plotting library in python"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"_ = plt.plot(data['num_doctors_fulltime'], data['num_nurses_fulltime'], 'rx')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You may be curious what the arguments we give to `plt.plot` are for, now\n",
"is the perfect time to look at the documentation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.plot?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We immediately note that some facilities have a lot of nurses, which\n",
"prevent's us seeing the detail of the main number of facilities. First\n",
"lets identify the facilities with the most nurses."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data[data['num_nurses_fulltime']>100]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we are using the command `data['num_nurses_fulltime']>100` to index\n",
"the facilities in the pandas data frame which have over 100 nurses. To\n",
"sort them in order we can also use the `sort` command. The result of\n",
"this command on its own is a data `Series` of `True` and `False` values.\n",
"However, when it is passed to the `data` data frame it returns a new\n",
"data frame which contains only those values for which the data series is\n",
"`True`. We can also sort the result. To sort the result by the values in\n",
"the `num_nurses_fulltime` column in *descending* order we use the\n",
"following command."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data[data['num_nurses_fulltime']>100].sort_values(by='num_nurses_fulltime', ascending=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We now see that the 'University of Calabar Teaching Hospital' is a large\n",
"outlier with 513 nurses. We can try and determine how much of an outlier\n",
"by histograming the data.\n",
"\n",
"## Plotting the Data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data['num_nurses_fulltime'].hist(bins=20) # histogram the data with 20 bins.\n",
"plt.title('Histogram of Number of Nurses')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can't see very much here. Two things are happening. There are so many\n",
"facilities with zero or one nurse that we don't see the histogram for\n",
"hospitals with many nurses. We can try more bins and using a *log* scale\n",
"on the $y$-axis."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data['num_nurses_fulltime'].hist(bins=100) # histogram the data with 20 bins.\n",
"plt.title('Histogram of Number of Nurses')\n",
"ax = plt.gca()\n",
"ax.set_yscale('log')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Question 1\n",
"\n",
"Read on the internet about the following python libraries: `numpy`,\n",
"`matplotlib`, `scipy` and `pandas`. What functionality does each provide\n",
"python?\n",
"\n",
"*10 marks*\n",
"\n",
"### Write your answer to Question 1 here\n",
"\n",
"Let's try and see how the number of nurses relates to the number of\n",
"doctors."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(figsize=(10, 7)) \n",
"ax.plot(data['num_doctors_fulltime'], data['num_nurses_fulltime'], 'rx')\n",
"ax.set_xscale('log') # use a logarithmic x scale\n",
"ax.set_yscale('log') # use a logarithmic Y scale\n",
"# give the plot some titles and labels\n",
"plt.title('Number of Nurses against Number of Doctors')\n",
"plt.ylabel('number of nurses')\n",
"plt.xlabel('number of doctors')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note a few things. We are interacting with our data. In particular, we\n",
"are replotting the data according to what we have learned so far. We are\n",
"using the progamming language as a *scripting* language to give the\n",
"computer one command or another, and then the next command we enter is\n",
"dependent on the result of the previous. This is a very different\n",
"paradigm to classical software engineering. In classical software\n",
"engineering we normally write many lines of code (entire object classes\n",
"or functions) before compiling the code and running it. Our approach is\n",
"more similar to the approach we take whilst debugging. Historically,\n",
"researchers interacted with data using a *console*. A command line\n",
"window which allowed command entry. The notebook format we are using is\n",
"slightly different. Each of the code entry boxes acts like a separate\n",
"console window. We can move up and down the notebook and run each part\n",
"in a different order. The *state* of the program is always as we left it\n",
"after running the previous part.\n",
"\n",
"# Probabilities \\[edit\\]\n",
"\n",
"We are now going to do some simple review of probabilities and use this\n",
"review to explore some aspects of our data.\n",
"\n",
"A probability distribution expresses uncertainty about the outcome of an\n",
"event. We often encode this uncertainty in a variable. So if we are\n",
"considering the outcome of an event, $Y$, to be a coin toss, then we\n",
"might consider $Y=1$ to be heads and $Y=0$ to be tails. We represent the\n",
"probability of a given outcome with the notation: $$\n",
"P(Y=1) = 0.5\n",
"$$ The first rule of probability is that the probability must normalize.\n",
"The sum of the probability of all events must equal 1. So if the\n",
"probability of heads ($Y=1$) is 0.5, then the probability of tails (the\n",
"only other possible outcome) is given by $$\n",
"P(Y=0) = 1-P(Y=1) = 0.5\n",
"$$\n",
"\n",
"Probabilities are often defined as the limit of the ratio between the\n",
"number of positive outcomes (e.g. *heads*) given the number of trials.\n",
"If the number of positive outcomes for event $y$ is denoted by $n$ and\n",
"the number of trials is denoted by $N$ then this gives the ratio $$\n",
"P(Y=y) = \\lim_{N\\rightarrow\n",
"\\infty}\\frac{n_y}{N}.\n",
"$$ In practice we never get to observe an event infinite times, so\n",
"rather than considering this we often use the following estimate $$\n",
"P(Y=y) \\approx \\frac{n_y}{N}.\n",
"$$\n",
"\n",
"## Probability and the NMIS Data \\[edit\\]\n",
"\n",
"Let's use the sum rule to compute the estimate the probability that a\n",
"facility has more than two nurses."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"large = (data.num_nurses_fulltime>2).sum() # number of positive outcomes (in sum True counts as 1, False counts as 0)\n",
"total_facilities = data.num_nurses_fulltime.count()\n",
"\n",
"prob_large = float(large)/float(total_facilities)\n",
"print(\"Probability of number of nurses being greather than 2 is:\", prob_large)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Conditioning\n",
"\n",
"When predicting whether a coin turns up head or tails, we might think\n",
"that this event is *independent* of the year or time of day. If we\n",
"include an observation such as time, then in a probability this is known\n",
"as *condtioning*. We use this notation, $P(Y=y|X=x)$, to condition the\n",
"outcome on a second variable (in this case the number of doctors). Or,\n",
"often, for a shorthand we use $P(y|x)$ to represent this distribution\n",
"(the $Y=$ and $X=$ being implicit). If two variables are independent\n",
"then we find that $$\n",
"P(y|x) = p(y).\n",
"$$ However, we might believe that the number of nurses is dependent on\n",
"the number of doctors. For this we can try estimating $P(Y>2 | X>1)$ and\n",
"compare the result, for example to $P(Y>2|X\\leq 1)$ using our empirical\n",
"estimate of the probability."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"large = ((data.num_nurses_fulltime>2) & (data.num_doctors_fulltime>1)).sum()\n",
"total_large_doctors = (data.num_doctors_fulltime>1).sum()\n",
"prob_both_large = large/total_large_doctors\n",
"print(\"Probability of number of nurses being greater than 2 given number of doctors is greater than 1 is:\", prob_both_large)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Question 2\n",
"\n",
"Write code that prints out the probability of nurses being greater than\n",
"2 for different numbers of doctors.\n",
"\n",
"*15 marks*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Write code for your answer to Question 2 in this box\n",
"# provide the answers so that the code runs correctly otherwise you will loose marks!\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Notes for Question\n",
"\n",
"Make sure the plot is included in *this* notebook file (the `IPython`\n",
"magic command `%matplotlib inline` we ran above will do that for you, it\n",
"only needs to be run once per file).\n",
"\n",
" Terminology Mathematical notation Description\n",
" ------------- ----------------------- ----------------------------------\n",
" joint $P(X=x, Y=y)$ prob. that X=x *and* Y=y\n",
" marginal $P(X=x)$ prob. that X=x *regardless of* Y\n",
" conditional $P(X=x\\vert Y=y)$ prob. that X=x *given that* Y=y\n",
"\n",
"\n",
"The different basic probability distributions.\n",
"\n",
"## A Pictorial Definition of Probability \\[edit\\]\n",
"\n",
"\n",
"\n",
"Figure: *Diagram representing the different probabilities, joint,\n",
"marginal and conditional. This diagram was inspired by lectures given by\n",
"Christopher Bishop.*\n",
"\n",
"[Inspired by lectures from Christopher Bishop]{style=\"text-align:right\"}\n",
"\n",
"## Definition of probability distributions\n",
"\n",
" ------------------------------------------------------------------------------------------------------\n",
" Terminology Definition Probability Notation\n",
" -------------- -------------------------------------------------------- ------------------------------\n",
" Joint $\\lim_{N\\rightarrow\\infty}\\frac{n_{X=3,Y=4}}{N}$ $P\\left(X=3,Y=4\\right)$\n",
" Probability \n",
"\n",
" Marginal $\\lim_{N\\rightarrow\\infty}\\frac{n_{X=5}}{N}$ $P\\left(X=5\\right)$\n",
" Probability \n",
"\n",
" Conditional $\\lim_{N\\rightarrow\\infty}\\frac{n_{X=3,Y=4}}{n_{Y=4}}$ $P\\left(X=3\\vert Y=4\\right)$\n",
" Probability \n",
" ------------------------------------------------------------------------------------------------------\n",
"\n",
"## Notational Details\n",
"\n",
"Typically we should write out $P\\left(X=x,Y=y\\right)$, but in practice\n",
"we often shorten this to $P\\left(x,y\\right)$. This looks very much like\n",
"we might write a multivariate function, *e.g.* $$\n",
" f\\left(x,y\\right)=\\frac{x}{y},\n",
" $$ but for a multivariate function $$\n",
"f\\left(x,y\\right)\\neq f\\left(y,x\\right).\n",
"$$ However, $$\n",
"P\\left(x,y\\right)=P\\left(y,x\\right)\n",
"$$ because $$\n",
"P\\left(X=x,Y=y\\right)=P\\left(Y=y,X=x\\right).\n",
"$$ Sometimes I think of this as akin to the way in Python we can write\n",
"'keyword arguments' in functions. If we use keyword arguments, the\n",
"ordering of arguments doesn't matter.\n",
"\n",
"We've now introduced conditioning and independence to the notion of\n",
"probability and computed some conditional probabilities on a practical\n",
"example The scatter plot of deaths vs year that we created above can be\n",
"seen as a *joint* probability distribution. We represent a joint\n",
"probability using the notation $P(Y=y, X=x)$ or $P(y, x)$ for short.\n",
"Computing a joint probability is equivalent to answering the\n",
"simultaneous questions, what's the probability that the number of nurses\n",
"was over 2 and the number of doctors was 1? Or any other question that\n",
"may occur to us. Again we can easily use pandas to ask such questions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"num_doctors = 1\n",
"large = (data.num_nurses_fulltime[data.num_doctors_fulltime==num_doctors]>2).sum()\n",
"total_facilities = data.num_nurses_fulltime.count() # this is total number of films\n",
"prob_large = float(large)/float(total_facilities)\n",
"print(\"Probability of nurses being greater than 2 and number of doctors being\", num_doctors, \"is:\", prob_large)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Product Rule\n",
"\n",
"This number is the joint probability, $P(Y, X)$ which is much *smaller*\n",
"than the conditional probability. The number can never be bigger than\n",
"the conditional probabililty because it is computed using the *product\n",
"rule*. $$\n",
"p(Y=y, X=x) = p(Y=y|X=x)p(X=x)\n",
"$$ and $$p(X=x)$$ is a probability distribution, which is equal or less\n",
"than 1, ensuring the joint distribution is typically smaller than the\n",
"conditional distribution.\n",
"\n",
"The product rule is a *fundamental* rule of probability, and you must\n",
"remember it! It gives the relationship between the two questions: 1)\n",
"What's the probability that a facility has over two nurses *and* one\n",
"doctor? and 2) What's the probability that a facility has over two\n",
"nurses *given that* it has one doctor?\n",
"\n",
"In our shorter notation we can write the product rule as $$\n",
"p(y, x) = p(y|x)p(x)\n",
"$$ We can see the relation working in practice for our data above by\n",
"computing the different values for $x=1$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"num_doctors=1\n",
"num_nurses=2\n",
"p_x = float((data.num_doctors_fulltime==num_doctors).sum())/float(data.num_nurses_fulltime.count())\n",
"p_y_given_x = float((data.num_nurses_fulltime[data.num_doctors_fulltime==num_doctors]>num_nurses).sum())/float((data.num_doctors_fulltime==num_doctors).sum())\n",
"p_y_and_x = float((data.num_nurses_fulltime[data.num_doctors_fulltime==num_doctors]>num_nurses).sum())/float(data.num_nurses_fulltime.count())\n",
"\n",
"print(\"P(x) is\", p_x)\n",
"print(\"P(y|x) is\", p_y_given_x)\n",
"print(\"P(y,x) is\", p_y_and_x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Sum Rule\n",
"\n",
"The other *fundamental rule* of probability is the *sum rule* this tells\n",
"us how to get a *marginal* distribution from the joint distribution.\n",
"Simply put it says that we need to sum across the value we'd like to\n",
"remove. $$\n",
"P(Y=y) = \\sum_{x} P(Y=y, X=x)\n",
"$$ Or in our shortened notation $$\n",
"P(y) = \\sum_{x} P(y, x)\n",
"$$\n",
"\n",
"### Question 3\n",
"\n",
"Write code that computes $P(y)$ by adding $P(y, x)$ for all values of\n",
"$x$.\n",
"\n",
"*10 marks*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Write code for your answer to Question 3 in this box\n",
"# provide the answers so that the code runs correctly otherwise you will loose marks!\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Bayes' Rule\n",
"\n",
"Bayes rule is a very simple rule, it's hardly worth the name of a rule\n",
"at all. It follows directly from the product rule of probability.\n",
"Because $P(y, x) = P(y|x)P(x)$ and by symmetry\n",
"$P(y,x)=P(x,y)=P(x|y)P(y)$ then by equating these two equations and\n",
"dividing through by $P(y)$ we have $$\n",
"P(x|y) =\n",
"\\frac{P(y|x)P(x)}{P(y)}\n",
"$$ which is known as Bayes' rule (or Bayes's rule, it depends how you\n",
"choose to pronounce it). It's not difficult to derive, and its\n",
"importance is more to do with the semantic operation that it enables.\n",
"Each of these probability distributions represents the answer to a\n",
"question we have about the world. Bayes rule (via the product rule)\n",
"tells us how to *invert* the probability.\n",
"\n",
"## Probabilities for Extracting Information from Data \\[edit\\]\n",
"\n",
"What use is all this probability in data science? Let's think about how\n",
"we might use the probabilities to do some decision making. Let's look at\n",
"the information data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data.columns"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Question 4\n",
"\n",
"Now we see we have several additional features. Let's assume we want to\n",
"predict `maternal_health_delivery_services`. How would we go about doing\n",
"it?\n",
"\n",
"Using what you've learnt about joint, conditional and marginal\n",
"probabilities, as well as the sum and product rule, how would you\n",
"formulate the question you want to answer in terms of probabilities?\n",
"Should you be using a joint or a conditional distribution? If it's\n",
"conditional, what should the distribution be over, and what should it be\n",
"conditioned on?\n",
"\n",
"*20 marks*\n",
"\n",
"### Write your answer to Question 4 here\n",
"\n",
"## Probabilistic Modelling \\[edit\\]\n",
"\n",
"This Bayesian approach is designed to deal with uncertainty arising from\n",
"fitting our prediction function to the data we have, a reduced data set.\n",
"\n",
"The Bayesian approach can be derived from a broader understanding of\n",
"what our objective is. If we accept that we can jointly represent all\n",
"things that happen in the world with a probability distribution, then we\n",
"can interogate that probability to make predictions. So, if we are\n",
"interested in predictions, $\\dataScalar_*$ at future points input\n",
"locations of interest, $\\inputVector_*$ given previously training data,\n",
"$\\dataVector$ and corresponding inputs, $\\inputMatrix$, then we are\n",
"really interogating the following probability density, $$\n",
"p(\\dataScalar_*|\\dataVector, \\inputMatrix, \\inputVector_*),\n",
"$$ there is nothing controversial here, as long as you accept that you\n",
"have a good joint model of the world around you that relates test data\n",
"to training data,\n",
"$p(\\dataScalar_*, \\dataVector, \\inputMatrix, \\inputVector_*)$ then this\n",
"conditional distribution can be recovered through standard rules of\n",
"probability\n",
"($\\text{data} + \\text{model} \\rightarrow \\text{prediction}$).\n",
"\n",
"We can construct this joint density through the use of the following\n",
"decomposition: $$\n",
"p(\\dataScalar_*|\\dataVector, \\inputMatrix, \\inputVector_*) = \\int p(\\dataScalar_*|\\inputVector_*, \\mappingMatrix) p(\\mappingMatrix | \\dataVector, \\inputMatrix) \\text{d} \\mappingMatrix\n",
"$$\n",
"\n",
"where, for convenience, we are assuming *all* the parameters of the\n",
"model are now represented by $\\parameterVector$ (which contains\n",
"$\\mappingMatrix$ and $\\mappingMatrixTwo$) and\n",
"$p(\\parameterVector | \\dataVector, \\inputMatrix)$ is recognised as the\n",
"posterior density of the parameters given data and\n",
"$p(\\dataScalar_*|\\inputVector_*, \\parameterVector)$ is the *likelihood*\n",
"of an individual test data point given the parameters.\n",
"\n",
"The likelihood of the data is normally assumed to be independent across\n",
"the parameters, $$\n",
"p(\\dataVector|\\inputMatrix, \\mappingMatrix) = \\prod_{i=1}^\\numData p(\\dataScalar_i|\\inputVector_i, \\mappingMatrix),$$\n",
"\n",
"and if that is so, it is easy to extend our predictions across all\n",
"future, potential, locations, $$\n",
"p(\\dataVector_*|\\dataVector, \\inputMatrix, \\inputMatrix_*) = \\int p(\\dataVector_*|\\inputMatrix_*, \\parameterVector) p(\\parameterVector | \\dataVector, \\inputMatrix) \\text{d} \\parameterVector.\n",
"$$\n",
"\n",
"The likelihood is also where the *prediction function* is incorporated.\n",
"For example in the regression case, we consider an objective based\n",
"around the Gaussian density, $$\n",
"p(\\dataScalar_i | \\mappingFunction(\\inputVector_i)) = \\frac{1}{\\sqrt{2\\pi \\dataStd^2}} \\exp\\left(-\\frac{\\left(\\dataScalar_i - \\mappingFunction(\\inputVector_i)\\right)^2}{2\\dataStd^2}\\right)\n",
"$$\n",
"\n",
"In short, that is the classical approach to probabilistic inference, and\n",
"all approaches to Bayesian neural networks fall within this path. For a\n",
"deep probabilistic model, we can simply take this one stage further and\n",
"place a probability distribution over the input locations, $$\n",
"p(\\dataVector_*|\\dataVector) = \\int p(\\dataVector_*|\\inputMatrix_*, \\parameterVector) p(\\parameterVector | \\dataVector, \\inputMatrix) p(\\inputMatrix) p(\\inputMatrix_*) \\text{d} \\parameterVector \\text{d} \\inputMatrix \\text{d}\\inputMatrix_*\n",
"$$ and we have *unsupervised learning* (from where we can get deep\n",
"generative models).\n",
"\n",
"## Graphical Models \\[edit\\]\n",
"\n",
"One way of representing a joint distribution is to consider conditional\n",
"dependencies between data. Conditional dependencies allow us to\n",
"factorize the distribution. For example, a Markov chain is a\n",
"factorization of a distribution into components that represent the\n",
"conditional relationships between points that are neighboring, often in\n",
"time or space. It can be decomposed in the following form.\n",
"$$p(\\dataVector) = p(\\dataScalar_\\numData | \\dataScalar_{\\numData-1}) p(\\dataScalar_{\\numData-1}|\\dataScalar_{\\numData-2}) \\dots p(\\dataScalar_{2} | \\dataScalar_{1})$$\n",
"\n",
"\n",
"\n",
"Figure: *A Markov chain is a simple form of probabilistic graphical\n",
"model providing a particular decomposition of the joint density.*\n",
"\n",
"By specifying conditional independencies we can reduce the\n",
"parameterization required for our data, instead of directly specifying\n",
"the parameters of the joint distribution, we can specify each set of\n",
"parameters of the conditonal independently. This can also give an\n",
"advantage in terms of interpretability. Understanding a conditional\n",
"independence structure gives a structured understanding of data. If\n",
"developed correctly, according to causal methodology, it can even inform\n",
"how we should intervene in the system to drive a desired result\n",
"[@Pearl:causality95].\n",
"\n",
"However, a challenge arises when the data becomes more complex. Consider\n",
"the graphical model shown below, used to predict the perioperative risk\n",
"of *C Difficile* infection following colon surgery\n",
"[@Steele:predictive12].\n",
"\n",
"\n",
"\n",
"Figure: *A probabilistic directed graph used to predict the\n",
"perioperative risk of *C Difficile* infection following colon surgery.\n",
"When these models have good predictive performance they are often\n",
"difficult to interpret. This may be due to the limited representation\n",
"capability of the conditional densities in the model.*\n",
"\n",
"To capture the complexity in the interelationship between the data, the\n",
"graph itself becomes more complex, and less interpretable.\n",
"\n",
"## Introduction to Classification \\[edit\\]\n",
"\n",
"Classification is perhaps the technique most closely assocated with\n",
"machine learning. In the speech based agents, on-device classifiers are\n",
"used to determine when the wake word is used. A wake word is a word that\n",
"wakes up the device. For the Amazon Echo it is \"Alexa\", for Siri it is\n",
"\"Hey Siri\". Once the wake word detected with a classifier, the speech\n",
"can be uploaded to the cloud for full processing, the speech recognition\n",
"stages.\n",
"\n",
"This isn't just useful for intelligent agents, the UN global pulse\n",
"project on public discussion on radio also uses [wake word detection for\n",
"recording radio conversations](https://radio.unglobalpulse.net/uganda/).\n",
"\n",
"A major breakthrough in image classification came in 2012 with the\n",
"ImageNet result of [Alex Krizhevsky, Ilya Sutskever and Geoff\n",
"Hinton](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-)\n",
"from the University of Toronto. ImageNet is a large data base of 14\n",
"million images with many thousands of classes. The data is used in a\n",
"community-wide challenge for object categorization. Krizhevsky et al\n",
"used convolutional neural networks to outperform all previous approaches\n",
"on the challenge. They formed a company which was purchased shortly\n",
"after by Google. This challenge, known as object categorisation, was a\n",
"major obstacle for practical computer vision systems. Modern object\n",
"categorization systems are close to human performance.\n",
"\n",
"Machine learning problems normally involve a prediction function and an\n",
"objective function. Regression is the case where the prediction function\n",
"iss over the real numbers, so the codomain of the functions,\n",
"$\\mappingFunction(\\inputMatrix)$ was the real numbers or sometimes real\n",
"vectors. The classification problem consists of predicting whether or\n",
"not a particular example is a member of a particular class. So we may\n",
"want to know if a particular image represents a digit 6 or if a\n",
"particular user will click on a given advert. These are classification\n",
"problems, and they require us to map to *yes* or *no* answers. That\n",
"makes them naturally discrete mappings.\n",
"\n",
"In classification we are given an input vector, $\\inputVector$, and an\n",
"associated label, $\\dataScalar$ which either takes the value $-1$ to\n",
"represent *no* or $1$ to represent *yes*.\n",
"\n",
"In supervised learning the inputs, $\\inputVector$, are mapped to a\n",
"label, $\\dataScalar$, through a function $\\mappingFunction(\\cdot)$ that\n",
"is dependent on a set of parameters, $\\weightVector$, $$\n",
"\\dataScalar = \\mappingFunction(\\inputVector; \\weightVector).\n",
"$$ The function $\\mappingFunction(\\cdot)$ is known as the *prediction\n",
"function*. The key challenges are (1) choosing which features,\n",
"$\\inputVector$, are relevant in the prediction, (2) defining the\n",
"appropriate *class of function*, $\\mappingFunction(\\cdot)$, to use and\n",
"(3) selecting the right parameters, $\\weightVector$.\n",
"\n",
"## Classification Examples \\[edit\\]\n",
"\n",
"- Classifiying hand written digits from binary images (automatic zip\n",
" code reading)\n",
"- Detecting faces in images (e.g. digital cameras).\n",
"- Who a detected face belongs to (e.g. Facebook, DeepFace)\n",
"- Classifying type of cancer given gene expression data.\n",
"- Categorization of document types (different types of news article on\n",
" the internet)\n",
"\n",
"## Bernoulli Distribution \\[edit\\]\n",
"\n",
"Our focus has been on models where the objective function is inspired by\n",
"a probabilistic analysis of the problem. In particular we've argued that\n",
"we answer questions about the data set by placing probability\n",
"distributions over the various quantities of interest. For the case of\n",
"binary classification this will normally involve introducing probability\n",
"distributions for discrete variables. Such probability distributions,\n",
"are in some senses easier than those for continuous variables, in\n",
"particular we can represent a probability distribution over\n",
"$\\dataScalar$, where $\\dataScalar$ is binary, with one value. If we\n",
"specify the probability that $\\dataScalar=1$ with a number that is\n",
"between 0 and 1, i.e. let's say that $P(\\dataScalar=1) = \\pi$ (here we\n",
"don't mean $\\pi$ the number, we are setting $\\pi$ to be a variable) then\n",
"we can specify the probability distribution through a table."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"$\\dataScalar$ 0 1\n",
" ------------------ ----------- -------\n",
" $P(\\dataScalar)$ $(1-\\pi)$ $\\pi$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Mathematically we can use a trick to implement this same table. We can\n",
"use the value $\\dataScalar$ as a mathematical switch and write that $$\n",
" P(\\dataScalar) = \\pi^\\dataScalar (1-\\pi)^{(1-\\dataScalar)}\n",
" $$ where our probability distribution is now written as a function of\n",
"$\\dataScalar$. This probability distribution is known as the [Bernoulli\n",
"distribution](http://en.wikipedia.org/wiki/Bernoulli_distribution). The\n",
"Bernoulli distribution is a clever trick for mathematically switching\n",
"between two probabilities if we were to write it as code it would be\n",
"better described as"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def bernoulli(y_i, pi):\n",
" if y_i == 1:\n",
" return pi\n",
" else:\n",
" return 1-pi"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we insert $\\dataScalar=1$ then the function is equal to $\\pi$, and if\n",
"we insert $\\dataScalar=0$ then the function is equal to $1-\\pi$. So the\n",
"function recreates the table for the distribution given above.\n",
"\n",
"The probability distribution is named for [Jacob\n",
"Bernoulli](http://en.wikipedia.org/wiki/Jacob_Bernoulli), the swiss\n",
"mathematician. In his book Ars Conjectandi he considered the\n",
"distribution and the result of a number of 'trials' under the Bernoulli\n",
"distribution to form the *binomial* distribution. Below is the page\n",
"where he considers Pascal's triangle in forming combinations of the\n",
"Bernoulli distribution to realise the binomial distribution for the\n",
"outcome of positive trials."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pods\n",
"pods.notebook.display_google_book(id='CF4UAAAAQAAJ', page='PA87')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"\n",
"Figure: *Jacob Bernoulli described the Bernoulli distribution through\n",
"an urn in which there are black and red balls.*\n",
"\n",
"Thomas Bayes also described the Bernoulli distribution, only he didn't\n",
"refer to Jacob Bernoulli's work, so he didn't call it by that name. He\n",
"described the distribution in terms of a table (think of a *billiard\n",
"table*) and two balls. Bayes suggests that each ball can be rolled\n",
"across the table such that it comes to rest at a position that is\n",
"*uniformly distributed* between the sides of the table.\n",
"\n",
"Let's assume that the first ball is rolled, and that it comes to reset\n",
"at a position that is $\\pi$ times the width of the table from the left\n",
"hand side.\n",
"\n",
"Now, we roll the second ball. We are interested if the second ball ends\n",
"up on the left side (+ve result) or the right side (-ve result) of the\n",
"first ball. We use the Bernoulli distribution to determine this.\n",
"\n",
"For this reason in Bayes's distribution there is considered to be\n",
"*aleatoric* uncertainty about the distribution parameter.\n",
"\n",
"\n",
"\n",
"Figure: *Thomas Bayes described the Bernoulli distribution\n",
"independently of Jacob Bernoulli. He used the analogy of a billiard\n",
"table. Any ball on the table is given a uniformly random position\n",
"between the left and right side of the table. The first ball\n",
"(\\colorBlack in the figure) gives the parameter of the Bernoulli\n",
"distribution. The second ball (\\colorRed in the figure) gives the\n",
"outcome as either left or right (relative to the first ball). This is\n",
"the origin of the term Bayesian because the parameter of the\n",
"distribution is drawn from a probsbility.*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pods\n",
"from ipywidgets import IntSlider"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pods.notebook.display_plots('bayes-billiard{counter:0>3}.svg', \n",
" directory='../slides/diagrams/ml', \n",
" counter=IntSlider(0,0,9,1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Maximum Likelihood in the Bernoulli \\[edit\\]\n",
"\n",
"Maximum likelihood in the Bernoulli distribution is straightforward.\n",
"Let's assume we have data, $\\dataVector$ which consists of a vector of\n",
"binary values of length $n$. If we assume each value was sampled\n",
"independently from the Bernoulli distribution, conditioned on the\n",
"parameter $\\pi$ then our joint probability density has the form $$\n",
"p(\\dataVector|\\pi) = \\prod_{i=1}^{\\numData} \\pi^{\\dataScalar_i} (1-\\pi)^{1-\\dataScalar_i}.\n",
"$$ As normal in maximum likelihood we consider the negative log\n",
"likelihood as our objective, $$\\begin{align*}\n",
" \\errorFunction(\\pi)& = -\\log p(\\dataVector|\\pi)\\\\ \n",
" & = -\\sum_{i=1}^{\\numData} \\dataScalar_i \\log \\pi - \\sum_{i=1}^{\\numData} (1-\\dataScalar_i) \\log(1-\\pi),\n",
" \\end{align*}$$\n",
"\n",
"and we can derive the gradient with respect to the parameter $\\pi$.\n",
"$$\\frac{\\text{d}\\errorFunction(\\pi)}{\\text{d}\\pi} = -\\frac{\\sum_{i=1}^{\\numData} \\dataScalar_i}{\\pi} + \\frac{\\sum_{i=1}^{\\numData} (1-\\dataScalar_i)}{1-\\pi},$$\n",
"\n",
"and as normal we look for a stationary point for the log likelihood by\n",
"setting this derivative to zero,\n",
"$$0 = -\\frac{\\sum_{i=1}^{\\numData} \\dataScalar_i}{\\pi} + \\frac{\\sum_{i=1}^{\\numData} (1-\\dataScalar_i)}{1-\\pi},$$\n",
"rearranging we form\n",
"$$(1-\\pi)\\sum_{i=1}^{\\numData} \\dataScalar_i = \\pi\\sum_{i=1}^{\\numData} (1-\\dataScalar_i),$$\n",
"which implies\n",
"$$\\sum_{i=1}^{\\numData} \\dataScalar_i = \\pi\\left(\\sum_{i=1}^{\\numData} (1-\\dataScalar_i) + \\sum_{i=1}^{\\numData} \\dataScalar_i\\right),$$\n",
"\n",
"and now we recognise that\n",
"$\\sum_{i=1}^{\\numData} (1-\\dataScalar_i) + \\sum_{i=1}^{\\numData} \\dataScalar_i = \\numData$\n",
"so we have\n",
"$$\\pi = \\frac{\\sum_{i=1}^{\\numData} \\dataScalar_i}{\\numData}$$\n",
"\n",
"so in other words we estimate the probability associated with the\n",
"Bernoulli by setting it to the number of observed positives, divided by\n",
"the total length of $\\dataScalar$. This makes intiutive sense. If I\n",
"asked you to estimate the probability of a coin being heads, and you\n",
"tossed the coin 100 times, and recovered 47 heads, then the estimate of\n",
"the probability of heads should be $\\frac{47}{100}$.\n",
"\n",
"### Exercise\n",
"\n",
"Show that the maximum likelihood solution we have found is a *minimum*\n",
"for our objective.\n",
"\n",
"### Write your answer to Exercise here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Use this box for any code you need for the exercise\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\text{posterior} =\n",
"\\frac{\\text{likelihood}\\times\\text{prior}}{\\text{marginal likelihood}}\n",
"$$\n",
"\n",
"Four components:\n",
"\n",
"1. Prior distribution\n",
"2. Likelihood\n",
"3. Posterior distribution\n",
"4. Marginal likelihood\n",
"\n",
"## Naive Bayes Classifiers \\[edit\\]\n",
"\n",
"*Note*: Everything we do below is possible using standard packages like\n",
"`scikit-learn`, our purpose in this session is to help you understand\n",
"how those engines are constructed. In practice for an application you\n",
"should use a library like `scikit-learn`.\n",
"\n",
"In probabilistic machine learning we place probability distributions (or\n",
"densities) over all the variables of interest, our first classification\n",
"algorithm will do just that. We will consider how to form a\n",
"classification by making assumptions about the *joint* density of our\n",
"observations. We need to make assumptions to reduce the number of\n",
"parameters we need to optimise.\n",
"\n",
"In the ideal world, given label data $\\dataVector$ and the inputs\n",
"$\\inputMatrix$ we should be able to specify the joint density of all\n",
"potential values of $\\dataVector$ and $\\inputMatrix$,\n",
"$p(\\dataVector, \\inputMatrix)$. If $\\inputMatrix$ and $\\dataVector$ are\n",
"our training data, and we can somehow extend our density to incorporate\n",
"future test data (by augmenting $\\dataVector$ with a new observation\n",
"$\\dataScalar^*$ and $\\inputMatrix$ with the corresponding inputs,\n",
"$\\inputVector^*$), then we can answer any given question about a future\n",
"test point $\\dataScalar^*$ given its covariates $\\inputVector^*$ by\n",
"conditioning on the training variables to recover, $$\n",
"p(\\dataScalar^*|\\inputMatrix, \\dataVector, \\inputVector^*),\n",
"$$\n",
"\n",
"We can compute this distribution using the product and sum rules.\n",
"However, to specify this density we must give the probability associated\n",
"with all possible combinations of $\\dataVector$ and $\\inputMatrix$.\n",
"There are $2^{\\numData}$ possible combinations for the vector\n",
"$\\dataVector$ and the probability for each of these combinations must be\n",
"jointly specified along with the joint density of the matrix\n",
"$\\inputMatrix$, as well as being able to *extend* the density for any\n",
"chosen test location $\\inputVector^*$.\n",
"\n",
"In naive Bayes we make certain simplifying assumptions that allow us to\n",
"perform all of the above in practice.\n",
"\n",
"## Data Conditional Independence\n",
"\n",
"If we are given model parameters $\\paramVector$ we assume that\n",
"conditioned on all these parameters that all data points in the model\n",
"are independent. In other words we have, $$\n",
" p(\\dataScalar^*, \\inputVector^*, \\dataVector, \\inputMatrix|\\paramVector) = p(\\dataScalar^*, \\inputVector^*|\\paramVector)\\prod_{i=1}^{\\numData} p(\\dataScalar_i, \\inputVector_i | \\paramVector).\n",
" $$ This is a conditional independence assumption because we are not\n",
"assuming our data are purely independent. If we were to assume that,\n",
"then there would be nothing to learn about our test data given our\n",
"training data. We are assuming that they are independent *given* our\n",
"parameters, $\\paramVector$. We made similar assumptions for regression,\n",
"where our parameter set included $\\mappingVector$ and $\\dataStd^2$.\n",
"Given those parameters we assumed that the density over\n",
"$\\dataVector, \\dataScalar^*$ was *independent*. Here we are going a\n",
"little further with that assumption because we are assuming the *joint*\n",
"density of $\\dataVector$ and $\\inputMatrix$ is independent across the\n",
"data given the parameters.\n",
"\n",
"Computing posterior distribution in this case becomes easier, this is\n",
"known as the 'Bayes classifier'.\n",
"\n",
"## Feature Conditional Independence\n",
"\n",
"$$\n",
"p(\\inputVector_i | \\dataScalar_i, \\paramVector) = \\prod_{j=1}^{\\dataDim} p(\\inputScalar_{i,j}|\\dataScalar_i, \\paramVector)\n",
"$$ where $\\dataDim$ is the dimensionality of our inputs.\n",
"\n",
"The assumption that is particular to naive Bayes is to now consider that\n",
"the *features* are also conditionally independent, but not only given\n",
"the parameters. We assume that the features are independent given the\n",
"parameters *and* the label. So for each data point we have\n",
"$$p(\\inputVector_i | \\dataScalar_i, \\paramVector) = \\prod_{j=1}^{\\dataDim} p(\\inputScalar_{i,j}|\\dataScalar_i,\\paramVector)$$\n",
"where $\\dataDim$ is the dimensionality of our inputs.\n",
"\n",
"## Marginal Density for $\\dataScalar_i$\n",
"\n",
"$$\n",
"p(\\inputScalar_{i,j},\\dataScalar_i| \\paramVector) = p(\\inputScalar_{i,j}|\\dataScalar_i, \\paramVector)p(\\dataScalar_i).\n",
"$$\n",
"\n",
"We now have nearly all of the components we need to specify the full\n",
"joint density. However, the feature conditional independence doesn't yet\n",
"give us the joint density over $p(\\dataScalar_i, \\inputVector_i)$ which\n",
"is required to subsitute in to our data conditional independence to give\n",
"us the full density. To recover the joint density given the conditional\n",
"distribution of each feature,\n",
"$p(\\inputScalar_{i,j}|\\dataScalar_i, \\paramVector)$, we need to make use\n",
"of the product rule and combine it with a marginal density for\n",
"$\\dataScalar_i$,\n",
"\n",
"$$p(\\inputScalar_{i,j},\\dataScalar_i| \\paramVector) = p(\\inputScalar_{i,j}|\\dataScalar_i, \\paramVector)p(\\dataScalar_i).$$\n",
"Because $\\dataScalar_i$ is binary the *Bernoulli* density makes a\n",
"suitable choice for our prior over $\\dataScalar_i$,\n",
"$$p(\\dataScalar_i|\\pi) = \\pi^{\\dataScalar_i} (1-\\pi)^{1-\\dataScalar_i}$$\n",
"where $\\pi$ now has the interpretation as being the *prior* probability\n",
"that the classification should be positive.\n",
"\n",
"## Joint Density for Naive Bayes\n",
"\n",
"This allows us to write down the full joint density of the training\n",
"data, $$\n",
" p(\\dataVector, \\inputMatrix|\\paramVector, \\pi) = \\prod_{i=1}^{\\numData} \\prod_{j=1}^{\\dataDim} p(\\inputScalar_{i,j}|\\dataScalar_i, \\paramVector)p(\\dataScalar_i|\\pi)\n",
" $$\n",
"\n",
"which can now be fit by maximum likelihood. As normal we form our\n",
"objective as the negative log likelihood,\n",
"\n",
"$$\\begin{align*}\n",
"\\errorFunction(\\paramVector, \\pi)& = -\\log p(\\dataVector, \\inputMatrix|\\paramVector, \\pi) \\\\ &= -\\sum_{i=1}^{\\numData} \\sum_{j=1}^{\\dataDim} \\log p(\\inputScalar_{i, j}|\\dataScalar_i, \\paramVector) - \\sum_{i=1}^{\\numData} \\log p(\\dataScalar_i|\\pi),\n",
"\\end{align*}$$ which we note *decomposes* into two objective functions,\n",
"one which is dependent on $\\pi$ alone and one which is dependent on\n",
"$\\paramVector$ alone so we have, $$\n",
"\\errorFunction(\\pi, \\paramVector) = \\errorFunction(\\paramVector) + \\errorFunction(\\pi).\n",
"$$ Since the two objective functions are separately dependent on the\n",
"parameters $\\pi$ and $\\paramVector$ we can minimize them independently.\n",
"Firstly, minimizing the Bernoulli likelihood over the labels we have, $$\n",
"\\errorFunction(\\pi) = -\\sum_{i=1}^{\\numData}\\log p(\\dataScalar_i|\\pi) = -\\sum_{i=1}^{\\numData} \\dataScalar_i \\log \\pi - \\sum_{i=1}^{\\numData} (1-\\dataScalar_i) \\log (1-\\pi)\n",
"$$ which we already minimized above recovering $$\n",
"\\pi = \\frac{\\sum_{i=1}^{\\numData} \\dataScalar_i}{\\numData}.\n",
"$$\n",
"\n",
"We now need to minimize the objective associated with the conditional\n",
"distributions for the features, $$\n",
"\\errorFunction(\\paramVector) = -\\sum_{i=1}^{\\numData} \\sum_{j=1}^{\\dataDim} \\log p(\\inputScalar_{i, j} |\\dataScalar_i, \\paramVector),\n",
"$$ which necessarily implies making some assumptions about the form of\n",
"the conditional distributions. The right assumption will depend on the\n",
"nature of our input data. For example, if we have an input which is real\n",
"valued, we could use a Gaussian density and we could allow the mean and\n",
"variance of the Gaussian to be different according to whether the class\n",
"was positive or negative and according to which feature we were\n",
"measuring. That would give us the form, $$\n",
"p(\\inputScalar_{i, j} | \\dataScalar_i,\\paramVector) = \\frac{1}{\\sqrt{2\\pi \\dataStd_{\\dataScalar_i,j}^2}} \\exp \\left(-\\frac{(\\inputScalar_{i,j} - \\mu_{\\dataScalar_i, j})^2}{\\dataStd_{\\dataScalar_i,j}^2}\\right),\n",
"$$ where $\\dataStd_{1, j}^2$ is the variance of the density for the\n",
"$j$th output and the class $\\dataScalar_i=1$ and $\\dataStd_{0, j}^2$ is\n",
"the variance if the class is 0. The means can vary similarly. Our\n",
"parameters, $\\paramVector$ would consist of all the means and all the\n",
"variances for the different dimensions.\n",
"\n",
"As normal we form our objective as the negative log likelihood, $$\n",
"\\errorFunction(\\paramVector, \\pi) = -\\log p(\\dataVector, \\inputMatrix|\\paramVector, \\pi) = -\\sum_{i=1}^{\\numData} \\sum_{j=1}^{\\dataDim} \\log p(\\inputScalar_{i, j}|\\dataScalar_i, \\paramVector) - \\sum_{i=1}^{\\numData} \\log p(\\dataScalar_i|\\pi),\n",
"$$ which we note *decomposes* into two objective functions, one which is\n",
"dependent on $\\pi$ alone and one which is dependent on $\\paramVector$\n",
"alone so we have, $$\n",
"\\errorFunction(\\pi, \\paramVector) = \\errorFunction(\\paramVector) + \\errorFunction(\\pi).\n",
"$$\n",
"\n",
"## Nigerian NMIS Data \\[edit\\]\n",
"\n",
"First we will load in the Nigerian NMIS health data. Our aim will be to\n",
"predict whether a center has maternal health delivery services given the\n",
"attributes in the data. We will predict of the number of nurses, the\n",
"number of doctors, location etc.\n",
"\n",
"Let's first remind ourselves of the data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we will convert this data into a form which we can use as inputs\n",
"`X`, and labels `y`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data = data[~pd.isnull(data['maternal_health_delivery_services'])]\n",
"data = data.dropna() # Remove entries with missing values\n",
"X = data[['emergency_transport',\n",
" 'num_chews_fulltime', \n",
" 'phcn_electricity',\n",
" 'child_health_measles_immun_calc',\n",
" 'num_nurses_fulltime',\n",
" 'num_doctors_fulltime', \n",
" 'improved_water_supply', \n",
" 'improved_sanitation',\n",
" 'antenatal_care_yn', \n",
" 'family_planning_yn',\n",
" 'malaria_treatment_artemisinin', \n",
" 'latitude', \n",
" 'longitude']].copy()\n",
"y = data['maternal_health_delivery_services']==True # set label to be whether there's a maternal health delivery service\n",
"\n",
"# Create series of health center types with the relevant index\n",
"s = data['facility_type_display'].apply(pd.Series, 1).stack() \n",
"s.index = s.index.droplevel(-1) # to line up with df's index\n",
"\n",
"# Extract from the series the unique list of types.\n",
"types = s.unique()\n",
"\n",
"# For each type extract the indices where it is present and add a column to X\n",
"type_names = []\n",
"for htype in types:\n",
" index = s[s==htype].index.tolist()\n",
" type_col=htype.replace(' ', '_').replace('/','-').lower()\n",
" type_names.append(type_col)\n",
" X.loc[:, type_col] = 0.0 \n",
" X.loc[index, type_col] = 1.0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This has given us a new data frame `X` which contains the different\n",
"facility types in different columns."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X.describe()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Naive Bayes NMIS \\[edit\\]\n",
"\n",
"We can now specify the naive Bayes model. For the genres we want to\n",
"model the data as Bernoulli distributed, and for the year and body count\n",
"we want to model the data as Gaussian distributed. We set up two data\n",
"frames to contain the parameters for the rows and the columns below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# assume data is binary or real.\n",
"# this list encodes whether it is binary or real (1 for binary, 0 for real)\n",
"binary_columns = ['emergency_transport',\n",
" 'phcn_electricity',\n",
" 'child_health_measles_immun_calc',\n",
" 'improved_water_supply', \n",
" 'improved_sanitation',\n",
" 'antenatal_care_yn', \n",
" 'family_planning_yn',\n",
" 'malaria_treatment_artemisinin'] + type_names\n",
"real_columns = ['num_chews_fulltime', \n",
" 'num_nurses_fulltime', \n",
" 'num_doctors_fulltime', \n",
" 'latitude', \n",
" 'longitude']\n",
"Bernoulli = pd.DataFrame(data=np.zeros((2,len(binary_columns))), columns=binary_columns, index=['theta_0', 'theta_1'])\n",
"Gaussian = pd.DataFrame(data=np.zeros((4,len(real_columns))), columns=real_columns, index=['mu_0', 'sigma2_0', 'mu_1', 'sigma2_1'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we have the data in a form ready for analysis, let's construct our\n",
"data matrix."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"num_train = 20000\n",
"indices = np.random.permutation(X.shape[0])\n",
"train_indices = indices[:num_train]\n",
"test_indices = indices[num_train:]\n",
"X_train = X.iloc[train_indices]\n",
"y_train = y.iloc[train_indices]==True\n",
"X_test = X.iloc[test_indices]\n",
"y_test = y.iloc[test_indices]==True"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And we can now train the model. For each feature we can make the fit\n",
"independently. The fit is given by either counting the number of\n",
"positives (for binary data) which gives us the maximum likelihood\n",
"solution for the Bernoulli. Or by computing the empirical mean and\n",
"variance of the data for the Gaussian, which also gives us the maximum\n",
"likelihood solution."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for column in X_train:\n",
" if column in Gaussian:\n",
" Gaussian[column]['mu_0'] = X_train[column][~y_train].mean()\n",
" Gaussian[column]['mu_1'] = X_train[column][y_train].mean()\n",
" Gaussian[column]['sigma2_0'] = X_train[column][~y_train].var(ddof=0)\n",
" Gaussian[column]['sigma2_1'] = X_train[column][y_train].var(ddof=0)\n",
" if column in Bernoulli:\n",
" Bernoulli[column]['theta_0'] = X_train[column][~y_train].sum()/(~y_train).sum()\n",
" Bernoulli[column]['theta_1'] = X_train[column][y_train].sum()/(y_train).sum()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can examine the nature of the distributions we've fitted to the model\n",
"by looking at the entries in these data frames."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Bernoulli"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The distributions show the parameters of the *independent* class\n",
"conditional probabilities for no maternity services. It is a Bernoulli\n",
"distribution with the parameter, $\\pi$, given by (`theta_0`) for the\n",
"facilities without maternity services and `theta_1` for the facilities\n",
"with maternity services. The parameters whow that, facilities with\n",
"maternity services also are more likely to have other services such as\n",
"grid electricity, emergency transport, immunization programs etc.\n",
"\n",
"The naive Bayes assumption says that the joint probability for these\n",
"services is given by the product of each of these Bernoulli\n",
"distributions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Gaussian"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We have modelled the numbers in our table with a Gaussian density. Since\n",
"several of these numbers are counts, a more appropriate distribution\n",
"might be the Poisson distribution. But here we can see that the average\n",
"number of nurses, healthworkers and doctors is *higher* in the\n",
"facilities with maternal services (`mu_1`) than those without maternal\n",
"services (`mu_0`). There is also a small difference between the mean\n",
"latitude and longitudes. However, the *standard deviation* which would\n",
"be given by the square root of the variance parameters (`sigma_0` and\n",
"`sigma_1`) is large, implying that a difference in latitude and\n",
"longitude may be due to sampling error. To be sure more analysis would\n",
"be required.\n",
"\n",
"The final model parameter is the prior probability of the positive\n",
"class, $\\pi$, which is computed by maximum likelihood."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"prior = float(y_train.sum())/len(y_train)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The prior probability tells us that slightly more facilities have\n",
"maternity services than those that don't.\n",
"\n",
"## Making Predictions\n",
"\n",
"Naive Bayes has given us the class conditional densities:\n",
"$p(\\inputVector_i | \\dataScalar_i, \\paramVector)$. To make predictions\n",
"with these densities we need to form the distribution given by $$\n",
"P(\\dataScalar^*| \\dataVector, \\inputMatrix, \\inputVector^*, \\paramVector)\n",
"$$ This can be computed by using the product rule. We know that $$\n",
"P(\\dataScalar^*| \\dataVector, \\inputMatrix, \\inputVector^*, \\paramVector)p(\\dataVector, \\inputMatrix, \\inputVector^*|\\paramVector) = p(\\dataScalar*, \\dataVector, \\inputMatrix, \\inputVector^*| \\paramVector)\n",
"$$ implying that $$\n",
"P(\\dataScalar^*| \\dataVector, \\inputMatrix, \\inputVector^*, \\paramVector) = \\frac{p(\\dataScalar*, \\dataVector, \\inputMatrix, \\inputVector^*| \\paramVector)}{p(\\dataVector, \\inputMatrix, \\inputVector^*|\\paramVector)}\n",
"$$ and we've already defined\n",
"$p(\\dataScalar^*, \\dataVector, \\inputMatrix, \\inputVector^*| \\paramVector)$\n",
"using our conditional independence assumptions above $$\n",
"p(\\dataScalar^*, \\dataVector, \\inputMatrix, \\inputVector^*| \\paramVector) = \\prod_{j=1}^{\\dataDim} p(\\inputScalar^*_{j}|\\dataScalar^*, \\paramVector)p(\\dataScalar^*|\\pi)\\prod_{i=1}^{\\numData} \\prod_{j=1}^{\\dataDim} p(\\inputScalar_{i,j}|\\dataScalar_i, \\paramVector)p(\\dataScalar_i|\\pi)\n",
"$$ The other required density is $$\n",
"p(\\dataVector, \\inputMatrix, \\inputVector^*|\\paramVector)\n",
"$$ which can be found from\n",
"$$p(\\dataScalar^*, \\dataVector, \\inputMatrix, \\inputVector^*| \\paramVector)$$\n",
"using the *sum rule* of probability, $$\n",
"p(\\dataVector, \\inputMatrix, \\inputVector^*|\\paramVector) = \\sum_{\\dataScalar^*=0}^1 p(\\dataScalar^*, \\dataVector, \\inputMatrix, \\inputVector^*| \\paramVector).\n",
"$$ Because of our independence assumptions that is simply equal to $$\n",
"p(\\dataVector, \\inputMatrix, \\inputVector^*| \\paramVector) = \\sum_{\\dataScalar^*=0}^1 \\prod_{j=1}^{\\dataDim} p(\\inputScalar^*_{j}|\\dataScalar^*_i, \\paramVector)p(\\dataScalar^*|\\pi)\\prod_{i=1}^{\\numData} \\prod_{j=1}^{\\dataDim} p(\\inputScalar_{i,j}|\\dataScalar_i, \\paramVector)p(\\dataScalar_i|\\pi).\n",
"$$ Substituting both forms in to recover our distribution over the test\n",
"label conditioned on the training data we have, $$\n",
"P(\\dataScalar^*| \\dataVector, \\inputMatrix, \\inputVector^*, \\paramVector) = \\frac{\\prod_{j=1}^{\\dataDim} p(\\inputScalar^*_{j}|\\dataScalar^*_i, \\paramVector)p(\\dataScalar^*|\\pi)\\prod_{i=1}^{\\numData} \\prod_{j=1}^{\\dataDim} p(\\inputScalar_{i,j}|\\dataScalar_i, \\paramVector)p(\\dataScalar_i|\\pi)}{\\sum_{\\dataScalar^*=0}^1 \\prod_{j=1}^{\\dataDim} p(\\inputScalar^*_{j}|\\dataScalar^*_i, \\paramVector)p(\\dataScalar^*|\\pi)\\prod_{i=1}^{\\numData} \\prod_{j=1}^{\\dataDim} p(\\inputScalar_{i,j}|\\dataScalar_i, \\paramVector)p(\\dataScalar_i|\\pi)}\n",
"$$ and we notice that all the terms associated with the training data\n",
"actually cancel, the test prediction is *conditionally independent* of\n",
"the training data *given* the parameters. This is a result of our\n",
"conditional independence assumptions over the data points. $$\n",
"p(\\dataScalar^*| \\inputVector^*, \\paramVector) = \\frac{\\prod_{j=1}^{\\dataDim} p(\\inputScalar^*_{j}|\\dataScalar^*_i,\n",
"\\paramVector)p(\\dataScalar^*|\\pi)}{\\sum_{\\dataScalar^*=0}^1 \\prod_{j=1}^{\\dataDim} p(\\inputScalar^*_{j}|\\dataScalar^*_i, \\paramVector)p(\\dataScalar^*|\\pi)}\n",
"$$ This formula is also fairly straightforward to implement. First we\n",
"implement the log probabilities for the Gaussian density."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def log_gaussian(x, mu, sigma2):\n",
" return -0.5* np.log(2*np.pi*sigma2)-((x-mu)**2)/(2*sigma2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now for any test point we compute the joint distribution of the Gaussian\n",
"features by *summing* their log probabilities. Working in log space can\n",
"be a considerable advantage over computing the probabilities directly:\n",
"as the number of features we include goes up, because all the\n",
"probabilities are less than 1, the joint probability will become smaller\n",
"and smaller, and may be difficult to represent accurately (or even\n",
"underflow). Working in log space can ameliorate this problem. We can\n",
"also compute the log probability for the Bernoulli distribution."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def log_bernoulli(x, theta):\n",
" return x*np.log(theta) + (1-x)*np.log(1-theta)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Laplace Smoothing\n",
"\n",
"Before we proceed, let's just pause and think for a moment what will\n",
"happen if `theta` here is either zero or one. This will result in\n",
"$\\log 0 = -\\infty$ and cause numerical problems. This definitely can\n",
"happen in practice. If some of the features are rare or very common\n",
"across the data set then the maximum likelihood solution could find\n",
"values of zero or one respectively. Such values are problematic because\n",
"they cause posterior probabilities of class membership of either one or\n",
"zero. In practice we deal with this using *Laplace smoothing* (which\n",
"actually has an interpretation as a Bayesian fit of the Bernoulli\n",
"distribution. Laplace used an example of the sun rising each day, and a\n",
"wish to predict the sun rise the following day to describe his idea of\n",
"smoothing, which can be found at the bottom of following page from\n",
"Laplace's 'Essai Philosophique ...'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pods\n",
"pods.notebook.display_google_book(id='1YQPAAAAQAAJ', page='PA16')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Laplace suggests that when computing the probability of an event where a\n",
"success or failure is rare (he uses an example of the sun rising across\n",
"the last 5,000 years or 1,826,213 days) that even though only successes\n",
"have been observed (in the sun rising case) that the odds for tomorrow\n",
"shouldn't be given as $$\n",
"\\frac{1,826,213}{1,826,213} = 1\n",
"$$ but rather by adding one to the numerator and two to the denominator,\n",
"$$\n",
"\\frac{1,826,213 + 1}{1,826,213 + 2} = 0.99999945.\n",
"$$ This technique is sometimes called a 'pseudocount technique' because\n",
"it has an intepretation of assuming some observations before you start,\n",
"it's as if instead of observing $\\sum_{i}\\dataScalar_i$ successes you\n",
"have an additional success, $\\sum_{i}\\dataScalar_i + 1$ and instead of\n",
"having observed $n$ events you've observed $\\numData + 2$. So we can\n",
"think of Laplace's idea saying (before we start) that we have 'two\n",
"observations worth of belief, that the odds are 50/50', because before\n",
"we start (i.e. when $\\numData=0$) our estimate is 0.5, yet because the\n",
"effective $n$ is only 2, this estimate is quickly overwhelmed by data.\n",
"Laplace used ideas like this a lot, and it is known as his 'principle of\n",
"insufficient reason'. His idea was that in the absence of knowledge\n",
"(i.e. before we start) we should assume that all possible outcomes are\n",
"equally likely. This idea has a modern counterpart, known as the\n",
"[principle of maximum\n",
"entropy](http://en.wikipedia.org/wiki/Principle_of_maximum_entropy). A\n",
"lot of the theory of this approach was developed by [Ed\n",
"Jaynes](http://en.wikipedia.org/wiki/Edwin_Thompson_Jaynes), who\n",
"according to his erstwhile collaborator and friend, John Skilling,\n",
"learnt French as an undergraduate by reading the works of Laplace.\n",
"Although John also related that Jaynes's spoken French was not up to the\n",
"standard of his scientific French. For me Ed Jaynes's work very much\n",
"carries on the tradition of Laplace into the modern era, in particular\n",
"his focus on Bayesian approaches. I'm very proud to have met those that\n",
"knew and worked with him. It turns out that Laplace's idea also has a\n",
"Bayesian interpretation (as Laplace understood), it comes from assuming\n",
"a particular prior density for the parameter $\\pi$, but we won't explore\n",
"that interpretation for the moment, and merely choose to estimate the\n",
"probability as, $$\n",
"\\pi = \\frac{\\sum_{i=1}^{\\numData} \\dataScalar_i + 1}{\\numData + 2}\n",
"$$ to prevent problems with certainty causing numerical issues and\n",
"misclassifications. Let's refit the Bernoulli features now."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# fit the Bernoulli with Laplace smoothing.\n",
"for column in X_train:\n",
" if column in Bernoulli:\n",
" Bernoulli[column]['theta_0'] = (X_train[column][~y_train].sum() + 1)/((~y_train).sum() + 2)\n",
" Bernoulli[column]['theta_1'] = (X_train[column][y_train].sum() + 1)/((y_train).sum() + 2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"That places us in a position to write the prediction function."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def predict(X_test, Gaussian, Bernoulli, prior):\n",
" log_positive = pd.Series(data = np.zeros(X_test.shape[0]), index=X_test.index)\n",
" log_negative = pd.Series(data = np.zeros(X_test.shape[0]), index=X_test.index)\n",
" for column in X_test.columns:\n",
" if column in Gaussian:\n",
" log_positive += log_gaussian(X_test[column], Gaussian[column]['mu_1'], Gaussian[column]['sigma2_1'])\n",
" log_negative += log_gaussian(X_test[column], Gaussian[column]['mu_0'], Gaussian[column]['sigma2_0'])\n",
" elif column in Bernoulli:\n",
" log_positive += log_bernoulli(X_test[column], Bernoulli[column]['theta_1'])\n",
" log_negative += log_bernoulli(X_test[column], Bernoulli[column]['theta_0'])\n",
" \n",
" v = np.zeros_like(log_positive.values)\n",
" for i in range(X_test.shape[0]):\n",
" v[i] = np.exp(log_positive.values[i] + np.log(prior))/(np.exp(log_positive.values[i] + np.log(prior)) \n",
" + np.exp(log_negative.values[i] + np.log(1-prior)))\n",
" return v\n",
" #return np.exp(log_positive + np.log(prior))/(np.exp(log_positive + np.log(prior)) + np.exp(log_negative + np.log(1-prior)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we are in a position to make the predictions for the test data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"p_y = predict(X_test, Gaussian, Bernoulli, prior)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can test the quality of the predictions in the following way.\n",
"Firstly, we can threshold our probabilities at 0.5, allocating points\n",
"with greater than 50% probability of membership of the positive class to\n",
"the positive class. We can then compare to the true values, and see how\n",
"many of these values we got correct. This is our total number correct."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"correct = y_test.eq(p_y>0.5)\n",
"total_correct = sum(correct)\n",
"print(\"Total correct\", total_correct, \" out of \", len(y_test), \"which is\", float(total_correct)/len(y_test), \"%\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also now plot the [confusion\n",
"matrix](http://en.wikipedia.org/wiki/Confusion_matrix). A confusion\n",
"matrix tells us where we are making mistakes. Along the diagonal it\n",
"stores the *true positives*, the points that were positive class that we\n",
"classified correctly, and the *true negatives*, the points that were\n",
"negative class and that we classified correctly. The off diagonal terms\n",
"contain the false positives and the false negatives. Along the rows of\n",
"the matrix we place the actual class, and along the columns we place our\n",
"predicted class."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"confusion_matrix = pd.DataFrame(data=np.zeros((2,2)), \n",
" columns=['predicted no maternity', 'predicted maternity'],\n",
" index =['actual no maternity','actual maternity'])\n",
"confusion_matrix['predicted maternity']['actual maternity'] = (y_test & (p_y>0.5)).sum()\n",
"confusion_matrix['predicted maternity']['actual no maternity'] = (~y_test & (p_y>0.5)).sum()\n",
"confusion_matrix['predicted no maternity']['actual maternity'] = (y_test & ~(p_y>0.5)).sum()\n",
"confusion_matrix['predicted no maternity']['actual no maternity'] = (~y_test & ~(p_y>0.5)).sum()\n",
"confusion_matrix"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise\n",
"\n",
"How can you improve your classification, are all the features equally\n",
"valid? Are some features more helpful than others? What happens if you\n",
"remove features that appear to be less helpful. How might you select\n",
"such features?\n",
"\n",
"### Write your answer to Exercise here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Use this box for any code you need for the exercise\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Exercise\n",
"\n",
"We have decided to classify positive if probability of maternity is\n",
"greater than 0.5. This has led us to accidentally classify some\n",
"facilities as havien't facilities for maternity when in fact they don't.\n",
"Imagine you wish to ensure that a facility handles maternity. With your\n",
"test set how low do you have to set the threshold to avoid all the false\n",
"negatives (i.e. facilities where you predicted there was no maternity,\n",
"but in actuality there were?\n",
"\n",
"### Write your answer to Exercise here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Use this box for any code you need for the exercise\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Making Predictions\n",
"\n",
"Naive Bayes has given us the class conditional densities:\n",
"$p(\\inputVector_i | \\dataScalar_i, \\paramVector)$. To make predictions\n",
"with these densities we need to form the distribution given by $$\n",
"P(\\dataScalar^*| \\dataVector, \\inputMatrix, \\inputVector^*, \\paramVector)\n",
"$$\n",
"\n",
"### Exercise\n",
"\n",
"Write down the negative log likelihood of the Gaussian density over a\n",
"vector of variables $\\inputVector$. Assume independence between each\n",
"variable. Minimize this objective to obtain the maximum likelihood\n",
"solution of the form. $$\n",
"\\mu = \\frac{\\sum_{i=1}^{\\numData} \\inputScalar_i}{\\numData}\n",
"$$ $$\n",
"\\dataStd^2 = \\frac{\\sum_{i=1}^{\\numData} (\\inputScalar_i - \\mu)^2}{\\numData}\n",
"$$\n",
"\n",
"### Write your answer to Exercise here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Use this box for any code you need for the exercise\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If the input data was *binary* then we could also make use of the\n",
"Bernoulli distribution for the features. For that case we would have the\n",
"form, $$\n",
"p(\\inputScalar_{i, j} | \\dataScalar_i,\\paramVector) = \\theta_{\\dataScalar_i, j}^{\\inputScalar_{i, j}}(1-\\theta_{\\dataScalar_i, j})^{(1-\\inputScalar_{i,j})},\n",
"$$ where $\\theta_{1, j}$ is the probability that the $j$th feature is on\n",
"if $\\dataScalar_i$ is 1.\n",
"\n",
"In either case, maximum likelihood fitting would proceed in the same\n",
"way. The objective has the form, $$\n",
"\\errorFunction(\\paramVector) = -\\sum_{j=1}^{\\dataDim} \\sum_{i=1}^{\\numData} \\log p(\\inputScalar_{i,j} |\\dataScalar_i, \\paramVector),\n",
"$$ and if, as above, the parameters of the distributions are specific to\n",
"each feature vector (we had means and variances for each continuous\n",
"feature, and a probability for each binary feature) then we can use the\n",
"fact that these parameters separate into disjoint subsets across the\n",
"features to write, $$\n",
"\\begin{align*}\n",
"\\errorFunction(\\paramVector) &= -\\sum_{j=1}^{\\dataDim} \\sum_{i=1}^{\\numData} \\log\n",
"p(\\inputScalar_{i,j} |\\dataScalar_i, \\paramVector_j)\\\\\n",
"& \\sum_{j=1}^{\\dataDim}\n",
"\\errorFunction(\\paramVector_j),\n",
"\\end{align*}\n",
"$$ which means we can minimize our objective on each feature\n",
"independently.\n",
"\n",
"These characteristics mean that naive Bayes scales very well with big\n",
"data. To fit the model we consider each feature in turn, we select the\n",
"positive class and fit parameters for that class, then we select each\n",
"negative class and fit features for that class. We have code below.\n",
"\n",
"## Naive Bayes Summary\n",
"\n",
"Naive Bayes is making very simple assumptions about the data, in\n",
"particular it is modeling the full *joint* probability of the data set,\n",
"$p(\\dataVector, \\inputMatrix | \\paramVector, \\pi)$ by very strong\n",
"assumptions about factorizations that are unlikely to be true in\n",
"practice. The data conditional independence assumption is common, and\n",
"relies on a rich parameter vector to absorb all the information in the\n",
"training data. The additional assumption of naive Bayes is that features\n",
"are conditional independent given the class label $\\dataScalar_i$ (and\n",
"the parameter vector, $\\paramVector$. This is quite a strong assumption.\n",
"However, it causes the objective function to decompose into parts which\n",
"can be independently fitted to the different feature vectors, meaning it\n",
"is very easy to fit the model to large data. It is also clear how we\n",
"should handle *streaming* data and *missing* data. This means that the\n",
"model can be run 'live', adapting parameters and information as it\n",
"arrives. Indeed, the model is even capable of dealing with new\n",
"*features* that might arrive at run time. Such is the strength of the\n",
"modeling the joint probability density. However, the factorization\n",
"assumption that allows us to do this efficiently is very strong and may\n",
"lead to poor decision boundaries in practice.\n",
"\n",
"## Other Reading\n",
"\n",
"- Chapter 5 of @Rogers:book11 up to pg 179 (Section 5.1, and 5.2 up to\n",
" 5.2.2).\n",
"\n",
"# References {#references .unnumbered}"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}