Skip to content

Commit

Permalink
use loop over while and related changes
Browse files Browse the repository at this point in the history
  • Loading branch information
quettabit committed Sep 6, 2022
1 parent 5ed1d28 commit 4a35ad6
Showing 1 changed file with 3 additions and 7 deletions.
10 changes: 3 additions & 7 deletions algorithms/linfa-clustering/src/k_means/algorithm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,13 +243,11 @@ impl<F: Float, R: Rng + Clone, DA: Data<Elem = F>, T, D: Distance<F>>
let n_runs = self.n_runs();

for _ in 0..n_runs {
let mut inertia = min_inertia;
let mut centroids =
self.init_method()
.run(self.dist_fn(), self.n_clusters(), observations, &mut rng);
let mut converged_iter: Option<u64> = None;
let mut n_iter = 0;
while n_iter < self.max_n_iterations() {
let (inertia, converged_iter) = loop {
update_memberships_and_dists(
self.dist_fn(),
&centroids,
Expand All @@ -258,17 +256,15 @@ impl<F: Float, R: Rng + Clone, DA: Data<Elem = F>, T, D: Distance<F>>
&mut dists,
);
let new_centroids = compute_centroids(&centroids, &observations, &memberships);
inertia = dists.sum();
let distance = self
.dist_fn()
.distance(centroids.view(), new_centroids.view());
centroids = new_centroids;
n_iter += 1;
if distance < self.tolerance() || n_iter == self.max_n_iterations() {
converged_iter = Some(n_iter);
break;
break (dists.sum(), Some(n_iter));
}
}
};

// We keep the centroids which minimize the inertia (defined as the sum of
// the squared distances of the closest centroid for all observations)
Expand Down

0 comments on commit 4a35ad6

Please sign in to comment.