# Parallel/distributed k-means clustering replicates

**URL:** <https://discourse.julialang.org/t/parallel-distributed-k-means-clustering-replicates/68963>\
**Category:** General Usage\
**Tags:** parallel, distributed, clustering\
**Created:** [September 29, 2021, 9:00pm UTC](https://discourse.julialang.org/t/parallel-distributed-k-means-clustering-replicates/68963 "2021-09-29T21:00:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![thompsonmj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/thompsonmj/32/25172_2.png) [@thompsonmj](https://discourse.julialang.org/u/thompsonmj)\
**Post date:** [September 29, 2021, 9:00pm UTC](https://discourse.julialang.org/t/parallel-distributed-k-means-clustering-replicates/68963/1 "2021-09-29T21:00:49Z")

</div>

First time trying parallel processing; I’d like to run replicates for the kmeans algorithm in parallel to find a global minimum.

Just calling `kmeans` on some data works fine:

```julia
using Clustering

n_data_points = 100000
data = rand(4,n_data_points)
n_clusters = 20
R = kmeans(data, n_clusters; maxiter=1000)

```

I tried using a parallel for loop, but get an error saying `BoundsError: attempt to access 0-element Vector{Float64} at index [1]`.

```julia
using Distributed
using SharedArrays

n_reps = 32
cost_R = SharedArray{Float64}(n_reps)
asgn_R = SharedArray{Int64}(n_data_points, n_reps)

addprocs()
@everywhere using Pkg
@everywhere Pkg.activate("..")
@everywhere using Clustering

@sync @distributed for repᵢ ∈ 1:n_reps
    R = kmeans(data, n_clusters; maxiter=1000)
    cost_R[repᵢ] = sum(R.costs)
    asgn_R[:,repᵢ] = assignments(R)
end

```

If I exclude `addprocs()` and run the loop, it executes alright.

---

<div class="post-metadata">

**Author:** ![thompsonmj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/thompsonmj/32/25172_2.png) [@thompsonmj](https://discourse.julialang.org/u/thompsonmj)\
**Post date:** [October 6, 2021, 3:34pm UTC](https://discourse.julialang.org/t/parallel-distributed-k-means-clustering-replicates/68963/2 "2021-10-06T15:34:20Z")

</div>

Putting `addprocs()` _before_ the SharedArrays solves the issue.

(Thanks Krystian Gulinski on Slack)
