Created
June 10, 2015 07:25
-
-
Save baruchel/75c4134a362cd0ebd1f5 to your computer and use it in GitHub Desktop.
Quick version of k-means with numpy written in a functional style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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