<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Analytique Bourassa on Medium]]></title>
        <description><![CDATA[Stories by Analytique Bourassa on Medium]]></description>
        <link>https://medium.com/@analytique.bourassa?source=rss-4f51cbb34427------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*hNBcqEWkgN6680cOeSDRsw.jpeg</url>
            <title>Stories by Analytique Bourassa on Medium</title>
            <link>https://medium.com/@analytique.bourassa?source=rss-4f51cbb34427------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:39:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@analytique.bourassa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Probabilistic Machine Learning Series Post 3: Weights Uncertainty with Correlated Noise]]></title>
            <link>https://medium.com/data-science/probabilistic-machine-learning-series-post-3-369cbf7ca8d3?source=rss-4f51cbb34427------2</link>
            <guid isPermaLink="false">https://medium.com/p/369cbf7ca8d3</guid>
            <category><![CDATA[machine-learing]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[probabilistic-models]]></category>
            <category><![CDATA[bidirectional-lstm]]></category>
            <dc:creator><![CDATA[Analytique Bourassa]]></dc:creator>
            <pubDate>Thu, 15 Sep 2022 20:36:50 GMT</pubDate>
            <atom:updated>2022-11-08T08:46:59.936Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using correlated dropout to quantify the uncertainty of Neural Network forecasts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZHJNx0xyn4_snDZgpTfsA.jpeg" /><figcaption>source: <a href="https://www.pexels.com/photo/question-mark-on-chalk-board-356079/">https://www.pexels.com/photo/question-mark-on-chalk-board-356079/</a></figcaption></figure><p>One of the main drawbacks of the Bayesian approach is that it is not scalable. In 2015, Blundell &amp; al. proposed to quantify the uncertainty in Neural Networks by using dropout. The method, called Bayes by backprop, uses the reparametrization trick to approximate a variational bound to the posterior. In this post, we will experiment with Bayes by backprop by making a few adjustments to the method. The main goal will be to see how we can add constrained parameters without adding constraints to our optimization problem (i.e. constraining the possible values of the parameters). The first modification is that we will make the dropout between different weights correlated by sampling from a normal multivariate distribution instead of independent normal distributions. This will be to account for the fact that the weights in the last layer will probably be correlated. The second aspect modified is that we will only use a Bayesian perspective only on the last layer of the neural net. This is to check if we can obtain a probabilistic model by adding as few parameters as possible.</p><h3>Origins of the loss function</h3><p>The loss function comes from the variational approximation. It is important to remember that the goal of the Bayesian framework is to find the posterior distribution. There are many ways to do this. One that has drawn attention in the last few years is the variational approach which provides a way to approximate the posterior in a scalable way. To achieve this, we convert the problem of finding the posterior into a continuous optimization problem where gradient descent (or similar techniques) can be applied. Instead of finding the exact posterior, it tries to find the closest solution given a set of parameters that describe the variational distribution. By closest solution, we mean the solution that minimizes the Kullback-Leibler divergence between the variational distribution and the posterior. In our case, the variational distribution will be the multivariate normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*z3CenutNhKMHe2RAqnO5tg.png" /><figcaption>The loss function replesenting the Kullback-Leibler divergence between the variational distribution and the posterior.</figcaption></figure><p>The loss function can be approximated by generating samples of the weights according to the variational distribution. It is decomposed into three different terms: the variational term, the likelihood, and the prior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*jV6AiIvov0ayvxRF4XrwxQ.png" /><figcaption>Loss approximated based on a randomly generated sample (dropout).</figcaption></figure><p>The likelihood will be modeled according to a normal distribution where the mean is given by the scalar product of the result of the last layer of the LSTM with the vector w and the variance is given by sigma. We can separate the parameters of the models into two main categories. The first one is the deterministic parameters; the LSTM parameters which try to give meaning to our data by acting as a features extractor. The second category is the ones defining the probabilistic distribution which are the μ vector, Σ matrix (the variational distribution, and the σ parameter. We thus generate α from a multivariate normal distribution parametrized by μ and Σ. The resulting weights will be multiplied (scalar product) with the last layer of the LSTM to give the mean ν of a univariate normal distribution with standard deviation σ which model the inherent noise of the observed quantity. In the graphical representation, dashed lines represent deterministic transformations while full lines indicate the parameter of a random variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*JF3cCO1gPcR4AbnhvlO8pQ.png" /><figcaption>Graphical representation of the relationship between the different parameters of the model. The dashed lines represented deterministic transformations while solid lines represent randomly sampled results based on the distributional parameters.</figcaption></figure><h3>How to get the covariance matrix</h3><p>A covariance matrix needs to satisfy some specific restrictions. It has to be symmetric and all the elements need to be positive. To be able to use automatic differentiation and satisfy those constraints, we used two transformations. The first one is to factorize the matrix using the <a href="https://en.wikipedia.org/wiki/Cholesky_decomposition">Cholesky factorization</a> of a positive definite matrix which gives us a symmetric matrix. The second transformation is to take the <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Softplus">softplus activation </a>function to make sure that all the elements are positives. The parameters that are trained are thus not the elements of the covariance matrix which would be constrained, but the parameters of the matrix L whose values can move freely on the real axis. Since the matrix product and the softplus function are both differentiable functions, we can construct a calculation graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*1dhqWZb4Gue2FoPvYLDcyQ.png" /><figcaption>Representation of the covariance matrix Sigma based on the matrix L. The coefficients of L are trained.</figcaption></figure><h3>Training phases</h3><p>The first training phase is about finding good LSTM weights for the task. We will consider the weights to be good if they give a good accuracy for the predictions and if the accuracy is stable over small perturbations of the weights. If the first phase, the loss function will be a usual loss for the task (here Mean Squared Error) which will give a maximum likelihood estimate. After a given number of steps, a Gaussian noise will be added to the weights to make sure that the obtained weights are stable. The noise added is equivalent to the diagonal elements of the covariance matrix that will be used in the second training phase. The parameters that are trained in this phase are the LSTM weights. The second training phase is about finding the full solution of the Bayesian parameters for the posterior. We will not only train the LSTM weights but also the covariance matrix. During both phases, early stopping was used.</p><h3>Predictions and calibration</h3><p>In the next figure, we can see the true values (in orange) are mostly in the confidence interval (blue shaded area).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZr7FHpgz1XW8RjoG2dX3g.png" /><figcaption>Forecasts (in blue) with the 95 % confidence interval (shaded blue) compared to the true values (orange).</figcaption></figure><p>Hopefully, this argument wasn’t convincing. We will thus look at the calibration of the probabilistic predictions. By calibration, we intuitively mean that 90 % of the predicted values should be below the inverse cumulative distribution function given for a 90% probability. There are many ways to measure calibration but we will only look at this one for the moment. We will represent visually the calibration by plotting the ratio of data that fall under the inverse cumulative distribution function as a function of the reference probability p which will be between 0 and 1. As we will see, there is a big difference depending on the random seed for the same training parameters. This phenomenon is quite recurrent as we fall into a local minimum and can’t escape from them. The simplest strategy is to do restarts whether it is from a new run or an existing run. In the first case, we hope that the algorithm will find a good local minimum with different initial conditions. In the latter case, the goal is to escape the local minima by resetting the learning rate to a higher value since it had decreased with every iteration before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*3jVB_WLsNROqZAnK-22Y4A.png" /><figcaption>Calibration curve for different restarts of the model training (i.e. different seeds).</figcaption></figure><h3>The word of the end</h3><p>We used simple modifications of the <a href="https://arxiv.org/pdf/1505.05424.pdf">Weights Uncertainty in Neural Networks</a> approach to see how to lift constraints of the distribution parameters without losing the advantages of automatic differentiation. The main idea is to make the trainable parameters move freely on the axis but transform them with differentiable functions which will give new parameters that satisfy the desired property.</p><h3>References and suggested readings</h3><p>[1] C. Blundell, . Cornebise, K. Kavukcuoglu and D. Wierstra, <a href="https://arxiv.org/pdf/1505.05424.pdf">Weight Uncertainty in Neural Networks</a> (2015) ICML</p><p>*All images unless otherwise noted are by the author.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=369cbf7ca8d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/probabilistic-machine-learning-series-post-3-369cbf7ca8d3">Probabilistic Machine Learning Series Post 3: Weights Uncertainty with Correlated Noise</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Probabilistic Machine Learning Series Post 2: Model Comparison]]></title>
            <link>https://medium.com/data-science/probabilistic-machine-learning-series-post-2-model-comparison-5c6504beb235?source=rss-4f51cbb34427------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c6504beb235</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <category><![CDATA[calibration]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[uncertainty]]></category>
            <dc:creator><![CDATA[Analytique Bourassa]]></dc:creator>
            <pubDate>Mon, 26 Aug 2019 17:19:55 GMT</pubDate>
            <atom:updated>2019-08-26T21:27:23.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sx8oBHePgUV9WV1pwX52QA.jpeg" /><figcaption><a href="https://www.pexels.com/photo/ask-blackboard-chalk-board-chalkboard-356079/">source</a></figcaption></figure><p>Many steps must be followed to transform raw data into a machine learning model. Those steps may be hard for non-experts and the <a href="https://www.forbes.com/sites/bernardmarr/2018/05/21/how-much-data-do-we-create-every-day-the-mind-blowing-stats-everyone-should-read/#53b2de8360ba">amount of data keeps growing</a>. A proposed solution to the <a href="https://www.forbes.com/sites/bernardmarr/2018/06/25/the-ai-skills-crisis-and-how-to-close-the-gap/#6d144a7d31f3">artificial intelligence skill crisis</a> is to do Automated Machine Learning (AutoML). Some notable projects are the <a href="https://cloud.google.com/automl/">Google Cloud AutoML</a> and the <a href="https://www.microsoft.com/en-us/research/project/automl/">Microsoft AutoML</a>. The problem of automated machine learning consists of different parts: neural architecture search, model selection, features engineering, model selection, hyperparameter tuning and model compression. In this post, we will be interested in model selection.</p><p>Model selection could be seen as a trivial task, but we will see that many metrics are needed to get a full picture of the quality of the model. The usual metric that comes to mind when selecting a model is the accuracy, but other factors need to be taken into account before moving forward. To explore this question, we will compare two similar model classes for the same dataset.</p><p>In a <a href="https://towardsdatascience.com/probabilistic-machine-learning-series-post-1-c8809652dd60">previous post</a>, we were able to do probabilistic forescasts for a time series. This raises the question of whether the probabilities predicted correpond to empirical frequencies which is called model calibration. Intuitively, for a classification problem, we would like that for the prediction with 80% confidence to have an accuracy of 80%. One might wonder why accuracy is not enough at the end. If the results are used in a decision process, overly confident results may lead to higher cost if the predictions are wrong and loss of opportunity in the case of under-confident predictions. For example, let’s suppose that we have a model to predict the presence of precious minerals in specific regions based on soil samples. Since exploration drilling for precious minerals can be time consuming and costly, the cost can be greatly reduced by focusing on high confidence prediction when the model is calibrated.</p><p>As Justin Timberlake showed us in the movie <a href="https://www.imdb.com/title/tt1637688/">In Time</a>, time can can be a currency so the next aspect that we will compare is the time needed to train a model. Despite the fact that we will use small dataset(i.e. the classical Iris data set), there is many reasons to keep track of the time needed to train a model. For example, some model testing technique based on resampling (ex: cross-validation and bootstrap) need to be trained multiple times with different samples of the data. Thus, the model will not be trained only once but many times. When the algorithm will be put into production, we should expect some bumps on the road (if not bumps, hopefully new data!) and it is important to know how much time it will take to retrain and redeploy the model. A good estimate of the time needed to train a model will also indicates if investment in bigger infrastructure is needed.</p><p>The final aspect (in the post) used to compare the model will be the prediction capacity/complexity of the model using the Widely-Applicable Information Criterion (WAIC). The criterion can be used to compare models on the same task that have completely different parameters <a href="http://www.stat.columbia.edu/~gelman/book/">[1]</a>. It is a Bayesian version of the standard AIC (Another Information Criterion or Alkeike Information Criterion).Information criterion can be viewed as an approximation to cross-validation, which may be time consuming <a href="http://www.stat.columbia.edu/~gelman/research/published/waic_understand3.pdf">[3]</a>.</p><h3>What are the data ?</h3><p>The data set used is a now a classic of machine learning: the Iris classification problem. The classification is based on the measurements of sepal and petal. <a href="https://onlinelibrary.wiley.com/doi/pdf/10.1111/j.1469-1809.1936.tb02137.x">The data were introduced by the British statistician and biologist Robert Fisher in 1936</a>. In the next figure, the distribution of the lengths and widths are displayed based on the species. A linear classifier should be able to make accurate classification except on the fringe of the virginica and versicolor species.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*C8kkEOZKJNDdgxhtpDa-cg.png" /><figcaption>Pairplots of the features which will be used for the classification. A linear classifier should be able to make accurate classification except on the fringe of the virginica and versicolor species.</figcaption></figure><h3>What are the models that we want to compare?</h3><p>A linear classifier will be trained for the classification problem. At first, a μ is calculated for each class using a linear combinaison of the features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*z1_dyRTxom87K_drlblg0g.png" /><figcaption>Equation for the calculation of μ for each of the k class using the N features.</figcaption></figure><p>The μ for each class it then used for our softmax function which provide a value (pₖ) between zero and one. This value (pₖ) will be the probability for the class indexed k.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*NOCjab37AkJaabsoAjRTbQ.png" /><figcaption>Softmax function for the probability p of belowing to the k class based on the previous calculation of μ.</figcaption></figure><p>In the first model, the β’s are all constant and equal to one. This will be called the model without temperatures (borrowing from the physics terminology since the function is anagolous the partition function in statistical physics). The second model will have a different β for each class which will add a little complexity to the model (more parameters) but hopefully will also give better results. The usage of temperature for calibration in machine learning can be found in the litterature <a href="https://arxiv.org/pdf/1507.04544.pdf">[4]</a><a href="https://arxiv.org/pdf/1905.00174.pdf">[5]</a>. Changing the temperatures will affect the relative scale for each μ when calculating the probabilities. As an example, we will suppose that μ₁ = 1, μ₂ = 2 and μ₃ = 3. By fixing all the initial temperatures to one, we have the probabilities p₁ = 0.09, p₂ = 0.24 and p₃ = 0.67. Let’s now keep the same temperatures β₂ = β₃ = 1 but increase the first temperature to two (β₁ = 2). The resulting probabilities have shifted to p₁ = 0.21, p₂ = 0.21 and p₃ = 0.58. Finally, if we reduce the first temperature to 0.5, the first probability will shift downward to p₁ = 0.06 and the others two will adjust to p₂ = 0.25 and p₃ = 0.69.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZh56dmv2TVpFC7YAM9-iw.png" /><figcaption>Summary of the resulting probabilities for differents temperatures by keeping the μ values fixed.</figcaption></figure><p>We represented the dependence between the parameters and the obervations in the following graphical model. The shaded circles are the observations. The z’s are the features (sepal length, sepal width, petal length and petal width) and the class is the species of the flower which is modeled with a categorical variable. The squares represent deterministic transformations of others variables such as μ and p whose equations have been given above. The circles are the stochastic parameters whose distribution we are trying to find (the θ’s and β’s). The boxes mean that the parameters are reapeated a number of times given by the constant at the bottom right corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSGCnvUF2u7tYmRDFBzkXA.png" /><figcaption>Graphical representation of the model with temperatures.</figcaption></figure><h3>Which model gives the best accuracy ?</h3><p>Despite that it is not the only important characteristic of a model, an inaccurate model might not be very useful. The accuracy was calculated for both models for 50 different trains/test splits (0.7/0.3). This was done because we wanted to compare the model classes and not a specific instance of the learned model. For a same model specification, many training factors will influence which specific model will be learned at the end. One of those factors will be the training data provided. Since the data set is small, the training/test split might induce big changes in the model obtained. As we can see in the next figure, the accuracy is on average slightly better for the model with temperatures with an average accuracy on the test set of 92.97 % (standard deviation: 4.50 %) compared to 90.93 % (standard deviation: 4.68 %) when there are no temperatures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5A7J6rFnj18GNUsM934JCw.png" /><figcaption>Distribution of accuracies of fifty different random train/test split for the model with and without temperatures. The model with temperatures has an average accuracy on the test set of 92.97 % (standard deviation: 4.50 %) compared to 90.93 % (standard deviation: 4.68 %) when there is no temperatures. The vertical lines are the corresponding means.</figcaption></figure><h3>What are the distributions of my parameters ?</h3><p>In the next two figures, we notice that the distribution of some the θ’s from the model with temperatures are more spread out than the ones from the model without temperatures. We usually want the values to be as peaked as possible. More spread out distribution means more uncertainty of the parameter value. The usual culprits that wehave encountered are bad priors, not enough sampling steps, model misspecification, etc. Since we want to compare the model classes in this case, we will keep those parameters fixed between each model training so only the model will change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4GIgf3AOYoMPhJM-x5uzg.png" /><figcaption>Distribution of the parameters for the model without temperatures. There is no distribution for the temperatures since the value is always a constant set to one.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aSA7l63G0GvJ35kjAdRjKQ.png" /><figcaption>Distribution of the parameters for the model with temperatures. There is a distribution for each blank circle in the graphical representation seen above.</figcaption></figure><h3>Are my probabilities trustworthy ?</h3><p>A probabilistic model can only base its probabilities on the data observed and the allowed representation given by the model specifications. In our example, we can only separate the classes based on a linear combination of the features. If this is not achievable, not only the accuracy will be bad, but we the calibration should not be good either. Before using those metrics, other signs based on the samples of the posterior will indicate that the model specified is not good for the data at hand. To measure the calibration, we will use the Static Calibration Error (SCE) <a href="https://arxiv.org/pdf/1904.01685.pdf">[2]</a> defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*QqKKUY8DM_X3eVJ-2VoFfQ.png" /></figure><p>The SCE <a href="https://arxiv.org/pdf/1904.01685.pdf">[2]</a> can be understood as follows. Separate the predictions in B time K bins where B in the number of confidence interval used for the calculation (ex: between 0 and 0.1, 0.1 and 0.2, etc) and K is the number of class. For each of those bins, take the absolute deviation between the observed accuracy, acc(b,k), and the expected accuracy, conf(b,k). Take the weighed sum of the confidence intervals bins with respect to the number of predictions in those bine. Finally, take the class average of the previous sum. The calibration curve of two trained models with the same accuracy of 89 % is shown to better understand the calibration metric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJuSS3ahDFHCgR9PRLN2cQ.png" /><figcaption>An exemple of calibration curve for two model with the same accuracy of 89 %. The model with the temperatures (blue) is better calibrated than the one without temperatures (orange). The green line is the perfect calibration line which means that we want the calibration curve to be as close as possible to this line. The dots are the values obtained for each of the eight intervals used.</figcaption></figure><p>The green line is the perfect calibration line which means that we want the calibration curve to be close to it. If we look at the high confidence prediction (0.70 and up), the model without temperature has a tendency to underestimate its confidence and to overestimate its confidence in the lower values (0.3 and down). The model with temperatures is generally better calibrated (mean SCE of 0.042 with a standard deviation of 0.007) than the model without temperature (mean SCE of 0.060 with a standard deviation of 0.006).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EqqWMQtAGOZ6ANHLmWJrg.png" /><figcaption>Distribution of SCE (a deviance calibration metric) of fifty different random train/test split for the model with and without temperatures. The model with temperatures (blue) is generally better calibrated (mean SCE of 0.042 with standard deviation of 0.007) than the model without temperature (orange) (mean SCE of 0.060 with standard deviation of 0.006). The vertical lines are the corresponding means.</figcaption></figure><h3>How long I have to wait ?</h3><p>As expected, the model with temperatures, which is more complex, takes more time to make the same number of iterations and samples. It took, on average 467 seconds (standard deviation of 37 seconds) to train the model with temperatures compared to 399 seconds (standard deviation of 4 seconds) for the model without temperatures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVtxU5zi6wut_hh-PFB2-A.png" /><figcaption>Computation times of fifty different random train/test split for the model with and without temperatures. It took on average 467 seconds (standard deviation of 37 seconds) to train the model with temperatures (blue) compared to 399 seconds (standard deviation of 4 seconds) for the model without temperatures (orange). The vertical lines are the corresponding means.</figcaption></figure><h3>What is the complexity added ?</h3><p>In this experiment, we compare the simpler model (without temperature) to a more complex one (with temperatures). An interesting metric to use is the Widely-Applicable Information Criterion which is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*r9XLKiAsDsMgNVG9TS7-4w.png" /></figure><p>where LPPD is the log pointwise predictive density and P is the effective number of parameters. The WAIC is used to estimate the out-of-sample predictive accuracy without using unobserved data <a href="http://www.stat.columbia.edu/~gelman/research/published/waic_understand3.pdf">[3]</a>. The lower the WAIC, the better since if the model fit well the data (high LPPD) the WAIC will get lower and an infinite number of effective parameters (infinite P) will give infinity. A model with an infinite number of effective parameters would be able to just memorize the data and thus would not be able to generalize well to new data. It is thus subtracted to correct the fact that it could fit the data well just by chance. The factor 2 comes from the historical reasons (it naturally comes from the original derivation of the Akaike Information Criterion based on the Kullback-Leibler divergence and the chi-squared distribution). The LPPD (log pointwise predictive density) is estimated with S samples from the posterior distribution as defined below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*ogN3AoS0NfYPYZ316sSw2A.png" /></figure><p>The numbers of effective parameters is estimated using the sum of the variances, with respect to the parameters, of the log-likelihood density (also called log predictive density) for each data point <a href="http://www.stat.columbia.edu/~gelman/research/published/waic_understand3.pdf">[3]</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*2kel-fCy5PDzu5EWggN-6A.png" /></figure><p>As we can see in the next figure, the WAIC for the model without temperatures is generally better (i.e. lower). One of the reasons might be the high variance of some of the parameters of the model with temperatures which will induce a higher effective number of parameters and may give a lower predictive density. One might expect the effective number of parameters between the two models to be the same since we can transform the model with temperature to the model without temperature by multiplying the θ’s by the corresponding β’s but the empirical evidence suggest otherwise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbYoADnEJkE5Q3mZNUaCQA.png" /><figcaption>Widely Applicable Information Criterion (WAIC) of fifty different random train/test split for the model with and without temperatures. The model without temperatures (orange) has a better WAIC, 247 with standard deviation of 12 , compared to the model with temperatures (orange), 539 with standard deviation of 60. The vertical lines are the corresponding means.</figcaption></figure><h3>Conclusion</h3><p>The next table summarizes the results obtained to compare the two model classes for the specific task. The model with temperatures has a better accuracy and calibration, but takes more computing time and has a worse WAIC (probably caused by the variance in the parameters).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yrgbyp94Oio8UoMChsHzNQ.png" /><figcaption>Summary of the mean results obtained for the metrics evaluated. The value in parenthesis is the standard deviation. The green dot indicate the better value of the two model classes while the red dots the worst value.</figcaption></figure><p>Since the computing time is not prohibitive compared to the gain in accuracy and calibration, the choice here is model with temperatures. Before putting it into production, one would probably gain by fine tuning it to reduce the uncertainty in the parameters where possible. One has to remember that the uncertainty also may give a higher calibration by avoiding overconfidence. We see that to get a full picture of the quality of a model class for a task, many metrics are needed. In the case of AutoML, the system would automatically use those metrics to select the best model. As we saw, we can gain by interpretating them according to the need of the user and the cost associated with the model usage. Fortunately for the data scientist, this also means that there is still a need for human jugement.</p><p>Thanks for reading</p><h3>References and suggested readings</h3><p>[1] A.Gelman, J. Carlin, H. Stern, D. Dunson, A. Vehtari, and D. Rubin, <a href="http://www.stat.columbia.edu/~gelman/book/">Bayesian Data Analysis</a> (2013), Chapman and Hall/CRC</p><p>[2] J. Nixon, M. Dusenberry, L. Zhang, G. Jerfel, D. Tran, <a href="https://arxiv.org/pdf/1904.01685.pdf">Measuring calibration in deep learning</a> (2019), ArXiv</p><p>[3] A. Gelman , J. Hwang, and A. Vehtari, <a href="http://www.stat.columbia.edu/~gelman/research/published/waic_understand3.pdf">Understanding predictive information criteria for Bayesian models</a> (2014), Springer Statistics and Computing</p><p>[4] A. Vehtari, A. Gelman, J. Gabry, Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC (2017), Springer Statistics and Computing</p><p>[5] A. Sadat Mozafari, H. Siqueira Gomes, W. Leão, C. Gagné, <a href="https://arxiv.org/pdf/1905.00174.pdf">Unsupervised Temperature Scaling: An Unsupervised Post-Processing Calibration Method of Deep Network</a> (2019), ICML 2019 Workshop on Uncertainty and Robustness in Deep Learning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c6504beb235" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/probabilistic-machine-learning-series-post-2-model-comparison-5c6504beb235">Probabilistic Machine Learning Series Post 2: Model Comparison</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Probabilistic Machine Learning Series Post 1]]></title>
            <link>https://medium.com/data-science/probabilistic-machine-learning-series-post-1-c8809652dd60?source=rss-4f51cbb34427------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8809652dd60</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[bayesian]]></category>
            <category><![CDATA[modeling]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Analytique Bourassa]]></dc:creator>
            <pubDate>Thu, 01 Aug 2019 21:27:38 GMT</pubDate>
            <atom:updated>2019-08-01T21:27:38.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sx8oBHePgUV9WV1pwX52QA.jpeg" /><figcaption>source: <a href="https://www.pexels.com/photo/ask-blackboard-chalk-board-chalkboard-356079/">https://www.pexels.com/photo/ask-blackboard-chalk-board-chalkboard-356079/</a></figcaption></figure><h3>Probabilistic Machine Learning Series Post 1: Using Neural Networks as part of a Bayesian model</h3><p>This series will be about different experiments and examples in probabilistic machine learning. The advantages of probabilistic machine learning is that we will be able to provide probabilistic predictions and that the we can separate the contributions from different parts of the model. In this first post, we will experiment using a neural network as part of a Bayesian model. This allows us to use the feature learning aspect of deep learning with the uncertainty estimates provided by the Bayesian framework. For those not familiar with the Bayesian framework, the <a href="https://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter1_Introduction/Ch1_Introduction_PyMC2.ipynb">first chapter of Probabilistic Programming and Bayesian Methods for Hackers</a> is suggested. In a nutshell, in the Bayesian framework, probabilities are seen as a degree of belief based on prior knowledge. The net result being that we will see the data as fixed and the parameters as random variables. Because of this, the parameters of our model will be represented by distributions. In comparison, in the frequentist framework, the parameters are fixed, but the data is random. The confidence interval representing the expected result of different samples. We will evaluate the posterior P(θ|y) using numerical methods. The posterior is proportional to the likelihood P(y|θ) times the prior P(θ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*fbrLcMk5IUvJRVxpc8dgfg.png" /><figcaption>The posterior, left-hand side, is proportional to the likelihood times the prior.</figcaption></figure><p>For our experiment, the main assumption is to train a Neural Network, as a feature extractor, to be used in a Bayesian linear regression. The Neural Network architecture is chosen accordingly to the type of data. Our example will be about time series forecasting so we will use a <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">LSTM</a> (Long Short Term Memory) neural network since it will be able to extract time dependencies. The main advantage of this complete separation of the Neural Network from the Bayesian model is that a pretrained Neural Network giving good features can be used as is to make probabilistic predictions. One of the disadvantages is that we lose the regularization aspect of Bayesian Deep Learning for the Neural Net which need to be achieved otherwise.</p><p>Our goal is to give a probabilistic forecast to a time series generated using only a short term time dependence, i.e. <a href="https://en.wikipedia.org/wiki/Autoregressive%E2%80%93moving-average_model">ARMA(4,2)</a>. The time series in seperated into two parts. The first one is the autoregressive AR(4) which means that the next value depends linearly on the last four values. The second part is the moving average part MA(2) which mean that the next value will also depend on the last two noise values. Those two parts combined constitute the ARMA(4,2) process. The LSTM will identify the structure in the time series while the Bayesian model will provided the probabilist estimates. In a first step, we will train a LSTM with a linear last layer which will mimic the Bayesian linear regression. Afterwards, we will include the LSTM as a feature extractor in our Bayesian model. We will describe the full model in the third section. The next three sections will be about</p><ul><li>Training the LSTM,</li><li>Describing the Bayesian model and</li><li>Making probabilistic predictions</li></ul><p>but let’s first take a look at the data generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09qGkEUkOIKaAaXdgIJ1sw.png" /></figure><p>Since the process is ARMA (4,2), we have only a short term dependency, no seasonality (nor cycles) and no trend. If we had those two components, further preprocessing would have been needed, but we want to stay in the happy path for this example. Before moving forward, I want to mention that the LSTM was implemented in PyTorch and the Bayesian model was implemented in <a href="https://docs.pymc.io/">PyMC3</a>.</p><h4>Step 1: Training the LSTM</h4><p>The LSTM was trained with sequences of seven time steps with the mean squared error loss. We used early stopping to prevent overfitting. We can see in the next figures that our predictions on the training set are close to the true values and that the errors can be well fitted using the Normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7LAlREMlMDvo-0NFUzcUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svMwrkdqje2hu3QF7PP77A.png" /></figure><p>We now have an accurate predictor for our time series that gives only point-wise predictions. In the next section, we will include it in a Bayesian model to obtain probabilistic predictions.</p><h4>Step 2: The Bayesian model</h4><p>First of all, we will look at a graphical representation of our model. White circles are stochastic nodes, shaded circle are observations and square node are the results of deterministic transformations. The full arrows points to the parameters of the stochastic node and the dashed line are deterministic transformations. We will start at y which is the value that we want to predict.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*KsDqUmSxyOaG-DoEvCPIiw.png" /><figcaption><strong>Figure 3: Graphical representation of our Bayesian model</strong></figcaption></figure><p>We suppose that y follows a Normal(μ, σ). μ is the equivalent of the predicted value of our LSTM which is defined by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*X9Yro98ZMwPW7AgR_PGmZg.png" /></figure><p>where z<em>ᵢ</em> are the last hidden state of our LSTM, θ<em>ᵢ</em> the weights of the linear layer, θₒ is the bias and n is the number of last hidden states of the LSTM. The main difference between the last layer of the LSTM model and the Bayesian model is that the weights and bias will be represented by a Normal distribution instead of being point estimates (i.e. single values). σ is the random error of the predictor that could not be captured by the uncertainty on the weights. At this point, z can be considered like a deterministic transformation done by the LSTM of the observed data. Since the uncertainty of the weights will not depend on the specific data values themselves, we only characterise the model uncertainty. The steps to include the LSTM in our Bayesian model are as follows:</p><ul><li>We trained the LSTM with a linear last layer</li><li>We remove the last layer and used the LSTM as a feature extractor</li><li>We replaced the original linear layer by a Bayesian linear regression</li></ul><p>Now that we know all the parameters of our model that we want to evaluate, let’s look at their distributions obtained using ADVI (<a href="https://arxiv.org/pdf/1603.00788.pdf">Automatic Differentiation Variational Inference</a>) and some fine tuning with MCMC (<a href="https://en.wikipedia.org/wiki/Markov_chain_Monte_Carlo">Markov Chain Monte Carlo</a>). Those inference numerical methods were combined by using the ADVI posterior as the MCMC prior which can be easily done in PyMC3. The ADVI method has the advantage of being scalable, but only gives an approximate posterior. The MCMC method is slower but converges to the exact posterior. In a further post, we will examine those in more details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AgwXLhfejTRTCUzZKaJoXw.png" /></figure><p>In this step, we have used the trained LSTM as part of a Bayesian model. We have obtained distributions for the parameters which were point estimates in the previous step. We are now ready to make probabilistic predictions.</p><h4>Step 3: Making probabilistic forecasts</h4><p>The forecasts are made using the Posterior Predictive Checks (i.e. the parameters of the model given the features are sampled to obtain the probabilistic forecast). We can see in the next figure the results with the 95% confidence interval. We can notice that most predictions are close to the true value and that most predictions fall in the confidence interval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCqOyEi9iyGFabZdohjtjw.png" /><figcaption>Time series predictions (blue) with 95% confidence interval (shaded blue) and the true values (orange)</figcaption></figure><p>Let’s do a small recap. We trained at LSTM on a time series to obtain accurate prediction. We could have stopped there, but we wanted a probabilistic prediction. Because of this, we used the LSTM as a feature extractor to be used in a Bayesian model. Since the Bayesian model parameters are represented by distributions, we could characterise the model uncertainty. The Bayesian model is then used to make probabilistic prediction using the posterior predictive checks. A lot of ideas are put together in this post. As stated earlier, this is part of a series of posts on probabilistic modeling so we will tackle some of the pieces individually in further posts.</p><p>Thanks for reading!</p><p><strong>References and suggested readings:</strong></p><p><a href="http://www.stat.columbia.edu/~gelman/book/"><em>[1]</em></a><em> </em>A. Gelman, J. Carlin, H. Stern, D. Dunson, A. Vehtari and D. Rubin<em>,</em> <a href="http://www.stat.columbia.edu/~gelman/book/"><em>Bayesian Data Analysis</em></a><em> (2013), </em>Chapman and Hall/CRC</p><p><a href="https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers"><em>[2] </em></a>C. Davidson-Pilon<em>, </em><a href="https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers"><em>Bayesian Methods for Hackers: Probabilistic Programming and Bayesian Inference</em></a><em> (2015), </em>Addison-Wesley Professional</p><p><a href="https://arxiv.org/pdf/1603.00788.pdf"><em>[3] </em></a>A. Kucukelbir, D. Tran, R. Ranganath, A. Gelman and D. M. Blei, <a href="https://arxiv.org/pdf/1603.00788.pdf"><em>Automatic Differentiation Variational Inference</em></a> (2016), ArXiv</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8809652dd60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/probabilistic-machine-learning-series-post-1-c8809652dd60">Probabilistic Machine Learning Series Post 1</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>