Skip to content

Instantly share code, notes, and snippets.

@baruchel
Created June 10, 2015 07:25
Show Gist options
  • Save baruchel/75c4134a362cd0ebd1f5 to your computer and use it in GitHub Desktop.
Save baruchel/75c4134a362cd0ebd1f5 to your computer and use it in GitHub Desktop.
Quick version of k-means with numpy written in a functional style
# -*- coding: utf-8 -*-
import numpy as np
import scipy.ndimage.measurements
import random
def kMeans( data, k, centers=None, iter=64 ):
if len(data.shape) == 1:
data = np.vstack(data)
if not centers:
centers = random.sample( data, k )
if type(centers) != np.ndarray:
centers = np.array( centers )
for i in range(iter):
centers = np.apply_along_axis(
scipy.ndimage.measurements.mean, 0, data,
np.argmin(
np.sum( (np.atleast_3d(data) - np.atleast_3d(centers).T)**2, axis=1 ),
axis = 1
),
range(k)
)
return centers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment