줄리아에서 클러스터링 패키지 사용하는 법
개요
줄리아에서는 클러스터링을 위한 패키지로써 Clustering.jl이 제공된다1. 구현되어 있는 알고리즘으로는 다음과 같은 것들이 있다:
- K-means
 - K-medoids
 - Affinity Propagation
 - Density-based spatial clustering of applications with noise (DBSCAN)
 - Markov Clustering Algorithm (MCL)
 - Fuzzy C-Means Clustering
 - Hierarchical Clustering
- Single Linkage
 - Average Linkage
 - Complete Linkage
 - Ward’s Linkage
 
 
코드
DBSCAN

DBSCAN(Density-based spatial clustering of applications with noise)은 dbscan() 함수로 구현되어 있다. $p$차원의 데이터가 $n$ 개 있다면, $p \times n$ 사이즈의 행렬과 반경radius이 인수로써 주어져야 한다.
julia> points = [iris.PetalLength iris.PetalWidth]'
2×150 adjoint(::Matrix{Float64}) with eltype Float64:
 1.4  1.4  1.3  1.5  1.4  1.7  1.4  1.5  1.4  1.5  1.5  …  5.4  5.6  5.1  5.1  5.9  5.7  5.2  5.0  5.2  5.4  5.1      
 0.2  0.2  0.2  0.2  0.2  0.4  0.3  0.2  0.2  0.1  0.2     2.1  2.4  2.3  1.9  2.3  2.5  2.3  1.9  2.0  2.3  1.8      
julia> dbscaned = dbscan(points, 0.5)
DbscanResult(DbscanCluster[DbscanCluster(50, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10  …  41, 42, 43, 44, 45, 46, 47, 48, 49, 50], Int64[]), DbscanCluster(100, [51, 52, 53, 54, 55, 56, 57, 58, 59, 60  …  141, 142, 143, 144, 145, 146, 147, 148, 149, 150], Int64[])], [1, 51], [50, 100], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1  …  2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
julia> dbscaned |> propertynames
(:clusters, :seeds, :counts, :assignments)
DBSCAN의 결과는 DbscanResult라는 구조체로 리턴된다. .assignments, .cluster 정도가 우리에게 필요하다.
각 클러스터 별로 어떤 데이터포인트가 속하는지는 다음과 같이 getproperty() 함수를 통해 얻을 수 있다.
julia> getproperty.(dbscaned.clusters, :core_indices)
2-element Vector{Vector{Int64}}:
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10  …  41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
 [51, 52, 53, 54, 55, 56, 57, 58, 59, 60  …  141, 142, 143, 144, 145, 146, 147, 148, 149, 150]
각각의 데이터포인트가 어떤 클러스터에 속하는지는 다음과 같이 .assignments 프로퍼티를 통해 알 수 있다.
julia> dbscaned.assignments
150-element Vector{Int64}:
 1
 1
 1
 1
 1
 1
 1
 1
 1
 1
 1
 1
 1
 1
 1
 ⋮
 2
 2
 2
 2
 2
 2
 2
 2
 2
 2
 2
 2
 2
 2
시각화에 대한 팁으로써, 클러스터는 임의의 정수로 배정되므로 점도표를 그릴 때 *.assignments를 그대로 color 옵션에 넣어 주면 다음과 같이 각 클러스터에 대응되는 색이 지정된다.
scatter(iris.PetalLength, iris.PetalWidth,
xlabel = "PetalLength", ylabel = "PetalWidth",
color = dbscaned.assignments)

클러스터링이 잘 수행된 것을 확인할 수 있다.
전체 코드
using Clustering
using RDatasets
iris = dataset("datasets", "iris")
scatter(iris.PetalLength, iris.PetalWidth, xlabel = "PetalLength", ylabel = "PetalWidth")
png("iris")
points = [iris.PetalLength iris.PetalWidth]'
dbscaned = dbscan(points, 0.5)
dbscaned |> propertynames
getproperty.(dbscaned.clusters, :core_indices)
dbscaned.assignments
scatter(iris.PetalLength, iris.PetalWidth,
xlabel = "PetalLength", ylabel = "PetalWidth",
color = dbscaned.assignments)
환경
- OS: Windows
 - julia: v1.9.0
 - Clustering v0.15.4
 

저희들의 저서 「줄리아 프로그래밍」이 2024 세종도서 학술부문에 선정되었습니다!

