Skip to content

Commit

Permalink
Support AbstractMatrix in fuzzy_cmeans
Browse files Browse the repository at this point in the history
  • Loading branch information
timholy committed Oct 2, 2018
1 parent 2753185 commit 5a45fcb
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/fuzzycmeans.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ struct FuzzyCMeansResult{T<:AbstractFloat} <: ClusteringResult
centers::Matrix{T} # cluster centers (d x C)
weights::Matrix{Float64} # assigned weights (n x C)
iterations::Int # number of elasped iterations
converged::Bool # wheather the procedure converged
converged::Bool # whether the procedure converged
end

## Utility functions
Expand Down Expand Up @@ -46,7 +46,7 @@ const _fcmeans_default_tol = 1.0e-3
const _fcmeans_default_display = :none

function fuzzy_cmeans(
data::Matrix{T},
data::AbstractMatrix{T},
C::Int,
fuzziness::Real;
maxiter::Int = _fcmeans_default_maxiter,
Expand All @@ -66,7 +66,7 @@ end
## Core implementation

function _fuzzy_cmeans(
data::Matrix{T}, # data matrix
data::AbstractMatrix{T}, # data matrix
C::Int, # total number of classes
fuzziness::Real, # fuzziness
maxiter::Int, # maximum number of iterations
Expand Down Expand Up @@ -113,3 +113,14 @@ function _fuzzy_cmeans(

FuzzyCMeansResult(centers, weights, iter, δ <= tol)
end

function Base.show(io::IO, result::FuzzyCMeansResult)
d, C = size(result.centers)
n, iter = size(result.weights, 1), result.iterations
print(io, "FuzzyCMeansResult: $C clusters for $n points in $d dimensions ")
if result.converged
print(io, "(converged in $iter iterations)")
else
print(io, "(failed to converge in $iter iterations)")
end
end
11 changes: 11 additions & 0 deletions test/fuzzycmeans.jl
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,15 @@ end
@test all(0 .<= r.weights .<= 1)
end

@testset "Abstract data matrix" begin
fuzziness = 2.0
Random.seed!(34568)
r = fuzzy_cmeans(view(x, :, :), k, fuzziness)
@test isa(r, FuzzyCMeansResult{Float64})
@test size(r.centers) == (m,k)
@test size(r.weights) == (n,k)
@test sum(r.weights, dims=2) fill(1.0, n)
@test all(0 .<= r.weights .<= 1)
end

end

0 comments on commit 5a45fcb

Please sign in to comment.