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

Specialize sample for sparse weights #943

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions src/sampling.jl
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,11 @@ sample(wv::AbstractWeights) = sample(default_rng(), wv)
sample(rng::AbstractRNG, a::AbstractArray, wv::AbstractWeights) = a[sample(rng, wv)]
sample(a::AbstractArray, wv::AbstractWeights) = sample(default_rng(), a, wv)

function sample(rng::AbstractRNG, wv::AbstractWeights{<:Real,T,V}) where {T<:Real,V<:SparseVector{T}}
Copy link
Member

Choose a reason for hiding this comment

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

This should be enough, right?

Suggested change
function sample(rng::AbstractRNG, wv::AbstractWeights{<:Real,T,V}) where {T<:Real,V<:SparseVector{T}}
function sample(rng::AbstractRNG, wv::AbstractWeights{<:Real,<:Real,<:SparseVector}

i = sample(rng, Weights(nonzeros(wv.values), sum(wv)))
return SparseArrays.nonzeroinds(wv.values)[i]
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
return SparseArrays.nonzeroinds(wv.values)[i]
return rowvals(wv.values)[i]

end

"""
direct_sample!([rng], a::AbstractArray, wv::AbstractWeights, x::AbstractArray)

Expand Down
3 changes: 2 additions & 1 deletion test/wsampling.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using StatsBase
using Random, Test, OffsetArrays
using Random, Test, OffsetArrays, SparseArrays

Random.seed!(1234)

Expand Down Expand Up @@ -41,6 +41,7 @@ for wv in (
weights([0.2, 0.8, 0.4, 0.6]),
weights([2, 8, 4, 6]),
weights(Float32[0.2, 0.8, 0.4, 0.6]),
weights(sparsevec([0, 8, 0, 6])),
Weights(Float32[0.2, 0.8, 0.4, 0.6], 2),
Weights([2, 8, 4, 6], 20.0),
)
Copy link
Member

Choose a reason for hiding this comment

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

It would make sense to also test line 137 below on sparse weights, right?

Expand Down
Loading