Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Weighted MLE fit for Laplace distribution with unit test #1310

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/univariate/continuous/laplace.jl
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,27 @@ function fit_mle(::Type{<:Laplace}, x::AbstractArray{<:Real})
xc .= abs.(x .- m)
return Laplace(m, mean(xc))
end

function fit_mle(::Type{<:Laplace}, x::AbstractArray{T}, w::AbstractArray{T}) where {T <: Real}
sp = sortperm(x)
n = length(x)
sw = sum(w)
highsum = sw
lowsum = zero(T)
idx = 0
for i = 1:n
lowsum += w[sp[i]]
highsum -= w[sp[i]]
if lowsum >= highsum
idx = sp[i]
break
end
end
μ = x[idx]
θ = zero(T)
for i = 1:length(x)
θ += w[i] * abs(x[i] - μ)
end
θ /= sw
return Laplace(μ, θ)
Comment on lines +125 to +146
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest to use AbstractWeights (from StatsBase) since this allows to use different types of weights and existing optimized algorithms. E.g., one should then probably just use median(x, weights) defined in StatsBase and mean(abs.(x .- m), weights) (also defined in StatsBase). This creates more memory allocations than in the unweighted case but I think it is fine since the code complexity (and hence the risk of introducing bugs) is much lower.

end
9 changes: 9 additions & 0 deletions test/fit.jl
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,15 @@ end
end
end

@testset "Testing fit for Laplace with weights" begin
for func in funcs, dist in (Laplace, Laplace{Float64})
d = fit(dist, func[2](dist(5.0, 3.0), N + 1), ones(Float64, N+1))
@test isa(d, dist)
@test isapprox(location(d), 5.0, atol=0.01)
@test isapprox(scale(d) , 3.0, atol=0.01)
end
end

@testset "Testing fit for Pareto" begin
for func in funcs, dist in (Pareto, Pareto{Float64})
x = func[2](dist(3., 7.), N)
Expand Down