Skip to content

Commit

Permalink
Merge pull request #140 from biaslab/fix-mv-normal-logpdf-gradient
Browse files Browse the repository at this point in the history
  • Loading branch information
ismailsenoz authored Oct 16, 2023
2 parents e9d869a + c5864af commit 31aac1b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
4 changes: 1 addition & 3 deletions src/distributions/normal_family/normal_family.jl
Original file line number Diff line number Diff line change
Expand Up @@ -667,9 +667,7 @@ getsufficientstatistics(::Type{MvNormalMeanCovariance}) = (identity, (x) -> x *
getlogpartition(::NaturalParametersSpace, ::Type{MvNormalMeanCovariance}) = (η) -> begin
(η₁, η₂) = unpack_parameters(MvNormalMeanCovariance, η)
k = length(η₁)
C = fastcholesky(-η₂)
l = logdet(C)
Cinv = LinearAlgebra.inv!(C)
Cinv, l = cholinv_logdet(-η₂)
return (dot(η₁, Cinv, η₁) / 2 - (k * log(2) + l)) / 2
end

Expand Down
31 changes: 31 additions & 0 deletions test/distributions/normal_family/normal_family_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -335,3 +335,34 @@ end
@test sort(svd(fi_dist).S) sort(svd(approxFisherInformation).S) rtol = 1e-1
end
end

@testitem "Diffrentiabilty of ExponentialFamily(ExponentialFamily.MvNormalMeanCovariance) logpdf" begin
include("./normal_family_setuptests.jl")
for i in 1:5, d in 2:3
rng = StableRNG(d * i)
μ = 10randn(rng, d)
L = LowerTriangular(randn(rng, d, d) + d * I)
Σ = L * L'
n_samples = 1
dist = MvNormalMeanCovariance(μ, Σ)

samples = rand(rng, dist, n_samples)

θ = pack_parameters(MvNormalMeanCovariance, (μ, Σ))
ef = convert(ExponentialFamilyDistribution, MvNormalMeanCovariance(μ, Σ))

nat_space2mean_space = (η) -> begin
dist = convert(Distribution, ExponentialFamilyDistribution(MvNormalMeanCovariance, η))
μ, Σ = mean(dist), cov(dist)
pack_parameters(MvNormalMeanCovariance, (μ, Σ))
end

for sample in eachcol(samples)
mean_gradient = ForwardDiff.gradient(Base.Fix2(gaussianlpdffortest, sample), θ)
nat_gradient = ForwardDiff.gradient((η) -> logpdf(ExponentialFamilyDistribution(MvNormalMeanCovariance, η), sample), getnaturalparameters(ef))
jacobian = ForwardDiff.jacobian(nat_space2mean_space, getnaturalparameters(ef))
#autograd failing to compute jacobian of matrix part correclty. Comparing only vector (mean) part.
@test nat_gradient[1:d] (jacobian'*mean_gradient)[1:d]
end
end
end

0 comments on commit 31aac1b

Please sign in to comment.