<?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 Sergio Caprioli on Medium]]></title>
        <description><![CDATA[Stories by Sergio Caprioli on Medium]]></description>
        <link>https://medium.com/@caprioli.sergio?source=rss-2fd7d7bed1da------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sdnS4bcZUj1fPsBNxGKgZA.jpeg</url>
            <title>Stories by Sergio Caprioli on Medium</title>
            <link>https://medium.com/@caprioli.sergio?source=rss-2fd7d7bed1da------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:37:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@caprioli.sergio/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[Generating synthetic correlation matrices with Variational Autoencoders]]></title>
            <link>https://medium.com/@caprioli.sergio/generating-synthetic-correlation-matrices-with-variational-autoencoders-8e7efe9a9faf?source=rss-2fd7d7bed1da------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e7efe9a9faf</guid>
            <dc:creator><![CDATA[Sergio Caprioli]]></dc:creator>
            <pubDate>Fri, 17 Feb 2023 11:10:06 GMT</pubDate>
            <atom:updated>2023-02-17T19:04:43.905Z</atom:updated>
            <content:encoded><![CDATA[<p>Variational Autoencoders (VAEs) are generative models based on a probabilistic architecture. The idea is similar to the Autoencoders, in which the input data is processed by an encoder which is a neural network used to “compress” the data into a lower dimension representation (called ”bottleneck”). Then another neural network, the decoder, reconstructs the original output. (<a href="https://en.wikipedia.org/wiki/Autoencoder">https://en.wikipedia.org/wiki/Autoencoder</a>).</p><p>A VAE follows a similar rationale, but the outputs of the encoder are the parameters of a Gaussian probability density and the inputs of the decoder are samples from that distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*hsBB5dDpwMcRQT9QK0sJog.jpeg" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:Gaussian_copula_gaussian_marginals.png">https://commons.wikimedia.org/wiki/File:Gaussian_copula_gaussian_marginals.png</a></figcaption></figure><p>In such architecture the “bottleneck” is stochastic. Therefore, we can say that the encoder outputs the parameters to q(z|x) while the decoder has in input the latent representation z and it outputs p(x|z).</p><p>(<a href="https://jaan.io/what-is-variational-autoencoder-vae-tutorial/">https://jaan.io/what-is-variational-autoencoder-vae-tutorial/</a>)</p><p>The loss function of the variational autoencoder has two components: the negative log-likelihood (i.e. the reconstruction loss) and a regularizer given by the Kullback-Leibler divergence between the encoder’s distribution q(z|x) and a prior p(z) on the latent factors z specified as a standard Normal distribution.</p><p>Usually VAEs are used for images generation (<a href="https://gaussian37.github.io/deep-learning-chollet-8-4/">https://gaussian37.github.io/deep-learning-chollet-8-4/</a>). Here we show a pytorch implementation to generate correlation matrices starting from a time series of log-returns of 44 market indices observed over 264 months.</p><p>First we define a dataset object that read a csv file and has a minmax scaler function.</p><pre>class CreateDataset(Dataset):<br>    <br>      def __init__(self, csv_file , minmax = True):<br>        <br>        self.data_df = np.genfromtxt(csv_file, delimiter=&#39;;&#39;)<br>        self.x = self.data_df[1:,1:]<br>        self.x = torch.as_tensor(self.x).float()<br>        <br>        if(minmax):<br>            for idx in range(self.x.size()[1]):<br>                <br>                dati = self.x<br>                self.x[:,idx] =  self.minmaxscaler(idx)<br><br>    <br>      def __getitem__(self, row):<br><br>        labels = self.data_df[0,1:]<br>        values = self.x[row,:]<br><br>        return values, labels<br><br>    <br>      def __len__(self):<br><br>        return len(self.x)<br>    <br>      def minmaxscaler(self,idx):<br>        return (self.x[:,idx]-self.x[:,idx].min())/(self.x[:,idx].max() - self.x[:,idx].min())</pre><p>From this dataset we define a loader that we use to sample 100 rows at a time and calculating for each sample a correlation matrix on the 44 variables. In this way we create a dataset of 220 correlation matrices that will be used to train the VAE.</p><p>The structure of the VAE and the loss are the following:</p><pre>LinearVAE(<br>  (enc1): Linear(in_features=1936, out_features=512, bias=True)<br>  (enc2): Linear(in_features=512, out_features=32, bias=True)<br>  (dec1): Linear(in_features=16, out_features=512, bias=True)<br>  (dec2): Linear(in_features=512, out_features=1936, bias=True)<br>)<br><br>def final_loss(bce_loss, mu, logvar):<br>    &quot;&quot;&quot;<br>    This function will add the reconstruction loss (BCELoss) and the <br>    KL-Divergence.<br>    KL-Divergence = 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)<br>    :param bce_loss: recontruction loss<br>    :param mu: the mean from the latent vector<br>    :param logvar: log variance from the latent vector<br>    &quot;&quot;&quot;<br>    BCE = bce_loss <br>    KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())<br>    return BCE + KLD</pre><p>We train the VAE on 100 epochs. We can check the results giving in input to the VAE a correlation matrix and comparing it with the reconstructed matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*4QUs5IZRt31fHIQq8IYTjQ.jpeg" /></figure><p>Finally, we can generate new correlation matrices sampling from the prior (a sampling from multivariate standard Normal) and using the decoder to produce synthetic correlation matrices.</p><pre>model.eval()<br>corr_sim = []<br>for i in range(100000):<br>    <br>    mu_value = torch.Tensor([0])<br>    mu_sim = mu_value.repeat(features)<br>    std_value = torch.Tensor([1])<br>    std_sim = std_value.repeat(features)<br>    mu = mu_sim # the first feature values as mean<br>    log_var = std_sim # the other feature values as variance<br>        # get the latent vector through reparameterization<br>    z = model.reparameterize(mu, log_var)<br> <br>        # decoding<br>    x = F.relu(model.dec1(z))<br>    reconstruction = torch.sigmoid(model.dec2(x))<br>    corr_sim.append(reconstruction)</pre><p>The following plots show the histograms of the “synthetic correlations”. It is worth noticing how the VAE has learned the symmetry of the matrices without imposing constraints. Of course, the generated matrices are not perfectly symmetric but observing the distributions of the “two sides” of each matrix, it is possible to split each simulated matrix into two matrices improving the efficiency of the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*5oIp3X6A5t1ZlQjgjGJArQ.jpeg" /><figcaption>Some generated correlations vs the empirical correlations calculated from the 220 sampled datasets</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e7efe9a9faf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bayesian variable selection]]></title>
            <link>https://medium.com/@caprioli.sergio/bayesian-variable-selection-9f2699169748?source=rss-2fd7d7bed1da------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f2699169748</guid>
            <category><![CDATA[bayesian-inference]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[variable-selection]]></category>
            <category><![CDATA[gibbs-sampling]]></category>
            <dc:creator><![CDATA[Sergio Caprioli]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 12:08:42 GMT</pubDate>
            <atom:updated>2023-01-18T17:08:14.684Z</atom:updated>
            <content:encoded><![CDATA[<p>A tutorial with Gibbs sampling and JAGS</p><p>Under the Bayesian approach to variable selection, rather than searching for a single optimal model, the idea is to estimate a posterior probability of all models within the considered class.</p><p>Given a dataset we define the hypotheses space H as the set of all possible models (e.g. all the combinations of explainatory variables X). We assign a prior probability to each model and then, updating the prior probability thrugh the likelihood P(X|H) we obtain the posterior P(H|D).</p><p>The estimation of the posterior probability distributions usually cannot be obtained in closed form solution, and it is necessary to use numerical procedures. Typically it is not possible to generate independent samples from the posteriors but it is necessary to use dependent samples where the next sample value depends on the value of the current sample. Dependent sampling is the core of the Monte Carlo Markov Chain (MCMC) procedures inference on the posterior distribution.</p><p>Here we will show the implementation of Bayesian Variable selection with Gibbs sampling. Gibbs sampling algorithm samples a parameter given the data and all the other parameters (at time t-1). It requires the marginal conditional posterior which is easy to represent in graphical model. We use JAGS (Just Another Gibbs Sampling) to run a Bayesian Variable selection using a hierarchichal model with indicator variables. JAGS (Just Another<br>Gibbs Sampler) is a program developed by Martyn Plummer that implements Bayesian inference using Markov Chain Monte Carlo models. Jags relies on BUGS language to define the models. It is a declarative language in which the programmer is requested only to specify the known relationship among the variables. The relations among the variables are specified in terms of a of a Directed Acyclic Graph (DAG) of probabilistic or deterministic functions. Likelihoods are defined when real data must be<br>taken into account. JAGS holds a list of sampler factory objects, which inspect the graph, recognize sets of parameters that can be updated with specific methods, and generate sampler objects for them. The list of sampler factories is traversed in order, starting with sampling methods<br>that are eﬀicient, but limited to certain specific model structures and ending with the most generic, possibly ineﬀicient, methods. If no suitable sampler can be generated for one of the model parameters, an error message is generated.</p><p>We use the hierarchical model presented in the ECB wotking paper of Giannone, Lenza, Primiceri “Economic predictions with big data: the illusion of sparsity”, described by the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Tsg-zgBYbjPdGxgXEAKRGQ.jpeg" /><figcaption>The hierarchical model of Giannone, Lenza, Primiceri</figcaption></figure><p>In such representation, there is an indicator variable modeled as a Bernoulli probability distribution, which governs the inclusion of each explanatory variable while the value of each coefficient is governed by a Gaussian distirbution with mean 0 and standard deviation gamma. Such parameter governs the shrinkage of the coefficients and the mapping of gamma over the R squared of the model, which in turn is modeled with a uniform prior, allows to avoid the calibration of the penalty parameter as typically seen in lasso and ridge regression.</p><p>To test such variable selection procedure, let’s simulate with R a dataset of 40 variables with a historical depth t = 60. We assume that the variables are a sample from a multivariate normal distirbution with a random correlation matrix. We use the R packages MASS and randocorr to simulate the explanatory variables aXX. Then we generate the dependent variable aYY as a linear combination of a subset of the 60 variables. The vector vP contains 1 for the first 8 coefficients and 0 elsewhere.</p><pre>library(MASS)<br>library(randcorr)<br><br>aNN_2 &lt;- c(60, 40)<br>Sigma &lt;- randcorr(aNN[2])<br><br> aXX &lt;- mvrnorm(n = 60, mu = rep(0, aNN[2]), Sigma = Sigma)<br>  aYY   &lt;- aXX %*% vP + aKsig * rnorm( aNN[ 1 ] )  <br>  aR2   &lt;- var( aXX %*% vP ) / var( aYY )<br>  aYY   &lt;- ( aYY - mean(aYY) ) / sd(aYY) </pre><p>The posteriors distribution of each parameter of the hierarchical model can be estimated with Gibbs sampling, using JAGS this can be obtained with the following code:</p><pre> y    &lt;- as.vector( aYY )   <br>  data &lt;- list(y = y,  X = aXX , n = aNN[1] , p = aNN[2] )    <br>  init &lt;- list( sigma = ini_sigma , betaT = rep(0,aNN[2]) , ind = rep(0,aNN[2]) )<br>  modelstring &lt;- &quot;<br>    model {<br>      for (i in 1:n) {<br>        mean[i] &lt;- inprod( X[i,] , beta )<br>        y[i]    ~  dnorm( mean[i] , 1 / ( sigma * sigma ) )<br>      }<br>      for (j in 1:p) {<br>        ind[j]    ~  dbern( 0.2 )     # NOTA!  fissa p_bin<br>        betaT[j]  ~  ddexp( 0 , 0.1  )  # NOTA!  fissa a_LL <br>        beta[j]   &lt;- ind[j] * betaT[j]  <br>      }<br>      sigma ~ dbeta( 2 , 2 )    <br>    }<br>  &quot;</pre><p>We simulate 100 datasets, for each dataset we generate the dependent variable with only 8 relevant (i.e. non zero) coefficients. The graphs below show the estimated posterior distributions of the 8 relevant coefficients (the red line shows the real value of the coefficiens) and those of the non relevant coefficients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*S2W0wt4hi7mO-t6FeJQoQg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f2699169748" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>