variance of conditional multivariate gaussian












0












$begingroup$


I was playing around with Gaussian Distributions on my machine and I was interesting in making a pretty plot. I wanted to show the distribution of $x_1$ if $x_2$ was given if $x_1,x_2$ were distributed by a multivariate normal distribution.



enter image description here



The image feels "wrong". I would imagine that the red likelihood in the center of the blue distribution would be wider than at the edge. After double checking the code, I notice it might be the maths.



Maths on wikipedia as well as my books confirm that the distribution of $x_1$ conditional on $x_2$ = $a$ is multivariate normal $(x_1 | x_2 = a) sim N(hat{mu}, hat{Sigma})$ where



$$
bar{boldsymbolmu}
=
boldsymbolmu_1 + boldsymbolSigma_{12} boldsymbolSigma_{22}^{-1}
left(
mathbf{a} - boldsymbolmu_2
right)
$$



and covariance matrix



$$
overline{boldsymbolSigma}
=
boldsymbolSigma_{11} - boldsymbolSigma_{12} boldsymbolSigma_{22}^{-1} boldsymbolSigma_{21}.
$$



When looking at the maths, it seems that the variance of $p(x_1|x_2 = a)$ does not depend on the value of $a$. This is starting to feel very counter intuitive so I am wondering if I am missing something.



The code that generated the plot



import matplotlib.pylab as plt 

import torch
from torch.distributions import Normal as norm
from torch.distributions.multivariate_normal import MultivariateNormal as mvnorm

#@title different given values { run: "auto" }
g1 = -3.5 #@param {type:"slider", min:-4, max:4, step:0.1}
g2 = 0.2 #@param {type:"slider", min:-4, max:4, step:0.1}
g3 = 2.9 #@param {type:"slider", min:-4, max:4, step:0.1}

m = torch.tensor([0.0, 0.0])
c = torch.tensor([[1.0, 0.9], [0.9, 1.0]])

s = mvnorm(m, c).sample(sample_shape=(5000,))
s_np = s.numpy().reshape(5000, 2)
plt.figure(figsize=(6,5))
plt.scatter(s_np[:, 0], s_np[:, 1], alpha=0.3)

for g in [g1, g2, g3]:
mu_pred = m[1] + c[0][1]/c[1][1]*(g - m[0])
sigma_pred = c[1][1] - c[1][0]/c[0][0]*c[0][1]
fitted_distr = norm(mu_pred, sigma_pred)
print(f"g:{g:.3}, mu:{mu_pred:.2}, sigma:{sigma_pred:.4}")

xs = torch.linspace(-4, 4, 300)
likelihood = torch.exp(fitted_distr.log_prob(xs)).numpy()

plt.plot(xs.numpy(), g + likelihood, c='red')









share|cite|improve this question









$endgroup$

















    0












    $begingroup$


    I was playing around with Gaussian Distributions on my machine and I was interesting in making a pretty plot. I wanted to show the distribution of $x_1$ if $x_2$ was given if $x_1,x_2$ were distributed by a multivariate normal distribution.



    enter image description here



    The image feels "wrong". I would imagine that the red likelihood in the center of the blue distribution would be wider than at the edge. After double checking the code, I notice it might be the maths.



    Maths on wikipedia as well as my books confirm that the distribution of $x_1$ conditional on $x_2$ = $a$ is multivariate normal $(x_1 | x_2 = a) sim N(hat{mu}, hat{Sigma})$ where



    $$
    bar{boldsymbolmu}
    =
    boldsymbolmu_1 + boldsymbolSigma_{12} boldsymbolSigma_{22}^{-1}
    left(
    mathbf{a} - boldsymbolmu_2
    right)
    $$



    and covariance matrix



    $$
    overline{boldsymbolSigma}
    =
    boldsymbolSigma_{11} - boldsymbolSigma_{12} boldsymbolSigma_{22}^{-1} boldsymbolSigma_{21}.
    $$



    When looking at the maths, it seems that the variance of $p(x_1|x_2 = a)$ does not depend on the value of $a$. This is starting to feel very counter intuitive so I am wondering if I am missing something.



    The code that generated the plot



    import matplotlib.pylab as plt 

    import torch
    from torch.distributions import Normal as norm
    from torch.distributions.multivariate_normal import MultivariateNormal as mvnorm

    #@title different given values { run: "auto" }
    g1 = -3.5 #@param {type:"slider", min:-4, max:4, step:0.1}
    g2 = 0.2 #@param {type:"slider", min:-4, max:4, step:0.1}
    g3 = 2.9 #@param {type:"slider", min:-4, max:4, step:0.1}

    m = torch.tensor([0.0, 0.0])
    c = torch.tensor([[1.0, 0.9], [0.9, 1.0]])

    s = mvnorm(m, c).sample(sample_shape=(5000,))
    s_np = s.numpy().reshape(5000, 2)
    plt.figure(figsize=(6,5))
    plt.scatter(s_np[:, 0], s_np[:, 1], alpha=0.3)

    for g in [g1, g2, g3]:
    mu_pred = m[1] + c[0][1]/c[1][1]*(g - m[0])
    sigma_pred = c[1][1] - c[1][0]/c[0][0]*c[0][1]
    fitted_distr = norm(mu_pred, sigma_pred)
    print(f"g:{g:.3}, mu:{mu_pred:.2}, sigma:{sigma_pred:.4}")

    xs = torch.linspace(-4, 4, 300)
    likelihood = torch.exp(fitted_distr.log_prob(xs)).numpy()

    plt.plot(xs.numpy(), g + likelihood, c='red')









    share|cite|improve this question









    $endgroup$















      0












      0








      0





      $begingroup$


      I was playing around with Gaussian Distributions on my machine and I was interesting in making a pretty plot. I wanted to show the distribution of $x_1$ if $x_2$ was given if $x_1,x_2$ were distributed by a multivariate normal distribution.



      enter image description here



      The image feels "wrong". I would imagine that the red likelihood in the center of the blue distribution would be wider than at the edge. After double checking the code, I notice it might be the maths.



      Maths on wikipedia as well as my books confirm that the distribution of $x_1$ conditional on $x_2$ = $a$ is multivariate normal $(x_1 | x_2 = a) sim N(hat{mu}, hat{Sigma})$ where



      $$
      bar{boldsymbolmu}
      =
      boldsymbolmu_1 + boldsymbolSigma_{12} boldsymbolSigma_{22}^{-1}
      left(
      mathbf{a} - boldsymbolmu_2
      right)
      $$



      and covariance matrix



      $$
      overline{boldsymbolSigma}
      =
      boldsymbolSigma_{11} - boldsymbolSigma_{12} boldsymbolSigma_{22}^{-1} boldsymbolSigma_{21}.
      $$



      When looking at the maths, it seems that the variance of $p(x_1|x_2 = a)$ does not depend on the value of $a$. This is starting to feel very counter intuitive so I am wondering if I am missing something.



      The code that generated the plot



      import matplotlib.pylab as plt 

      import torch
      from torch.distributions import Normal as norm
      from torch.distributions.multivariate_normal import MultivariateNormal as mvnorm

      #@title different given values { run: "auto" }
      g1 = -3.5 #@param {type:"slider", min:-4, max:4, step:0.1}
      g2 = 0.2 #@param {type:"slider", min:-4, max:4, step:0.1}
      g3 = 2.9 #@param {type:"slider", min:-4, max:4, step:0.1}

      m = torch.tensor([0.0, 0.0])
      c = torch.tensor([[1.0, 0.9], [0.9, 1.0]])

      s = mvnorm(m, c).sample(sample_shape=(5000,))
      s_np = s.numpy().reshape(5000, 2)
      plt.figure(figsize=(6,5))
      plt.scatter(s_np[:, 0], s_np[:, 1], alpha=0.3)

      for g in [g1, g2, g3]:
      mu_pred = m[1] + c[0][1]/c[1][1]*(g - m[0])
      sigma_pred = c[1][1] - c[1][0]/c[0][0]*c[0][1]
      fitted_distr = norm(mu_pred, sigma_pred)
      print(f"g:{g:.3}, mu:{mu_pred:.2}, sigma:{sigma_pred:.4}")

      xs = torch.linspace(-4, 4, 300)
      likelihood = torch.exp(fitted_distr.log_prob(xs)).numpy()

      plt.plot(xs.numpy(), g + likelihood, c='red')









      share|cite|improve this question









      $endgroup$




      I was playing around with Gaussian Distributions on my machine and I was interesting in making a pretty plot. I wanted to show the distribution of $x_1$ if $x_2$ was given if $x_1,x_2$ were distributed by a multivariate normal distribution.



      enter image description here



      The image feels "wrong". I would imagine that the red likelihood in the center of the blue distribution would be wider than at the edge. After double checking the code, I notice it might be the maths.



      Maths on wikipedia as well as my books confirm that the distribution of $x_1$ conditional on $x_2$ = $a$ is multivariate normal $(x_1 | x_2 = a) sim N(hat{mu}, hat{Sigma})$ where



      $$
      bar{boldsymbolmu}
      =
      boldsymbolmu_1 + boldsymbolSigma_{12} boldsymbolSigma_{22}^{-1}
      left(
      mathbf{a} - boldsymbolmu_2
      right)
      $$



      and covariance matrix



      $$
      overline{boldsymbolSigma}
      =
      boldsymbolSigma_{11} - boldsymbolSigma_{12} boldsymbolSigma_{22}^{-1} boldsymbolSigma_{21}.
      $$



      When looking at the maths, it seems that the variance of $p(x_1|x_2 = a)$ does not depend on the value of $a$. This is starting to feel very counter intuitive so I am wondering if I am missing something.



      The code that generated the plot



      import matplotlib.pylab as plt 

      import torch
      from torch.distributions import Normal as norm
      from torch.distributions.multivariate_normal import MultivariateNormal as mvnorm

      #@title different given values { run: "auto" }
      g1 = -3.5 #@param {type:"slider", min:-4, max:4, step:0.1}
      g2 = 0.2 #@param {type:"slider", min:-4, max:4, step:0.1}
      g3 = 2.9 #@param {type:"slider", min:-4, max:4, step:0.1}

      m = torch.tensor([0.0, 0.0])
      c = torch.tensor([[1.0, 0.9], [0.9, 1.0]])

      s = mvnorm(m, c).sample(sample_shape=(5000,))
      s_np = s.numpy().reshape(5000, 2)
      plt.figure(figsize=(6,5))
      plt.scatter(s_np[:, 0], s_np[:, 1], alpha=0.3)

      for g in [g1, g2, g3]:
      mu_pred = m[1] + c[0][1]/c[1][1]*(g - m[0])
      sigma_pred = c[1][1] - c[1][0]/c[0][0]*c[0][1]
      fitted_distr = norm(mu_pred, sigma_pred)
      print(f"g:{g:.3}, mu:{mu_pred:.2}, sigma:{sigma_pred:.4}")

      xs = torch.linspace(-4, 4, 300)
      likelihood = torch.exp(fitted_distr.log_prob(xs)).numpy()

      plt.plot(xs.numpy(), g + likelihood, c='red')






      probability-distributions normal-distribution






      share|cite|improve this question













      share|cite|improve this question











      share|cite|improve this question




      share|cite|improve this question










      asked Jan 6 at 8:38









      Vincent WarmerdamVincent Warmerdam

      15217




      15217






















          1 Answer
          1






          active

          oldest

          votes


















          0












          $begingroup$

          This question was also asked on another stack-exchange website and that question has been answered there.






          share|cite|improve this answer









          $endgroup$













            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "69"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            noCode: true, onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmath.stackexchange.com%2fquestions%2f3063616%2fvariance-of-conditional-multivariate-gaussian%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0












            $begingroup$

            This question was also asked on another stack-exchange website and that question has been answered there.






            share|cite|improve this answer









            $endgroup$


















              0












              $begingroup$

              This question was also asked on another stack-exchange website and that question has been answered there.






              share|cite|improve this answer









              $endgroup$
















                0












                0








                0





                $begingroup$

                This question was also asked on another stack-exchange website and that question has been answered there.






                share|cite|improve this answer









                $endgroup$



                This question was also asked on another stack-exchange website and that question has been answered there.







                share|cite|improve this answer












                share|cite|improve this answer



                share|cite|improve this answer










                answered Jan 15 at 10:21









                Vincent WarmerdamVincent Warmerdam

                15217




                15217






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Mathematics Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmath.stackexchange.com%2fquestions%2f3063616%2fvariance-of-conditional-multivariate-gaussian%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Quarter-circle Tiles

                    build a pushdown automaton that recognizes the reverse language of a given pushdown automaton?

                    Mont Emei