Skip to content

Commit 80eca28

Browse files
authored
Merge pull request #14 from TuringLang/tor/turing-diag-normal-extras
added length, params, and entropy for TuringDiagNormal
2 parents a28e134 + b8e274c commit 80eca28

File tree

3 files changed

+20
-4
lines changed

3 files changed

+20
-4
lines changed

Project.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
1010
PDMats = "90014a1f-27ba-587c-ab20-58faa44d9150"
1111
Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
1212
SpecialFunctions = "276daf66-3868-5448-9aa4-cd146d93841b"
13+
StatsBase = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
1314
StatsFuns = "4c63d2b9-4356-54db-8cca-17b64c39e42c"
1415
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
1516
Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"

src/multivariate.jl

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,10 @@ struct TuringDiagMvNormal{Tm<:AbstractVector, Tσ<:AbstractVector} <: Continuous
3030
σ::Tσ
3131
end
3232

33+
Distributions.params(d::TuringDiagMvNormal) = (d.m, d.σ)
34+
Distributions.dim(d::TuringDiagMvNormal) = length(d.m)
3335
Base.length(d::TuringDiagMvNormal) = length(d.m)
34-
Base.size(d::TuringDiagMvNormal) = (length(d), length(d))
35-
function Distributions.rand(rng::Random.AbstractRNG, d::TuringDiagMvNormal)
36-
return d.m .+ d.σ .* randn(rng, length(d))
37-
end
36+
Base.size(d::TuringDiagMvNormal) = (length(d), )
3837
function Distributions.rand(rng::Random.AbstractRNG, d::TuringDiagMvNormal, n::Int)
3938
return d.m .+ d.σ .* randn(rng, length(d), n)
4039
end
@@ -79,6 +78,12 @@ function _logpdf(d::TuringDenseMvNormal, x::AbstractMatrix)
7978
return -((size(x, 1) * log(2π) + logdet(d.C)) .+ vec(sum(abs2.(zygote_ldiv(d.C.U', x .- d.m)), dims=1))) ./ 2
8079
end
8180

81+
import StatsBase: entropy
82+
function entropy(d::TuringDiagMvNormal)
83+
T = eltype(d.σ)
84+
return (length(d) * (T(log2π) + one(T)) / 2 + sum(log.(d.σ)))
85+
end
86+
8287
# zero mean, dense covariance
8388
MvNormal(A::TrackedMatrix) = TuringMvNormal(A)
8489

test/others.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
using StatsBase: entropy
2+
13
@testset "Others" begin
24
@test fill(param(1.0), 3) isa TrackedArray
35
x = rand(3)
@@ -11,3 +13,11 @@
1113
B = copy(A)
1214
@test DistributionsAD.zygote_ldiv(A, B) == A \ B
1315
end
16+
17+
@testset "Extras from StatsBase.jl" begin
18+
sigmas = exp.(randn(10))
19+
d1 = TuringDiagMvNormal(zeros(10), sigmas)
20+
d2 = MvNormal(zeros(10), sigmas)
21+
22+
@test entropy(d1) == entropy(d2)
23+
end

0 commit comments

Comments
 (0)