#!/usr/bin/env python
# coding: utf-8
# This was input cell with execution count: 1
import os
import numpy as np
from helper_functions import *
# Please don't modify this cell
# This was input cell with execution
...
#!/usr/bin/env python
# coding: utf-8
# This was input cell with execution count: 1
import os
import numpy as np
from helper_functions import *
# Please don't modify this cell
# This was input cell with execution count:
def get_initial_means(array, k):
"""
Picks k random points from the 2D array
(without replacement) to use as initial
cluster means
params:
array = numpy.ndarray[numpy.ndarray[float]] - m x n | datapoints x features
k = int
returns:
initial_means = numpy.ndarray[numpy.ndarray[float]]
"""
newArr = array.copy()
np.random.shuffle(newArr) # First shuffle up the array (so we don't need to
worry about random selection)
return newArr[:k] # Select k values to return
# This was input cell with execution count:
def dist(a, b, axis=1):
"""
Euclidean Distance metric
"""
return np.linalg.norm(a - b, axis=axis)
def k_means_step(image_values, k, means):
"""
A single update/step of the K-means algorithm
Based on a input image_values and current mean estimate
calculate new means and predict clusters for each of the pixel
params:
image_values = numpy.ndarray[numpy.ndarray[numpy.ndarray[float]]]
k = int
initial_means = numpy.ndarray[numpy.ndarray[float]]
returns:
new_means = numpy.ndarray[numpy.ndarray[float]]
clusters = numpy.ndarray[numpy.ndarray[int]]
"""
new_means = np.ndarray(shape=(k, len(image_values[0])), dtype=float)
clusters = np.zeros(shape=len(image_values), dtype=int)
meanPts = []
for i in range(k):
meanPts.append(
[]) # For meanPts, we group all points by their corresponding
cluster so we can calculate the new means
eucDist = np.zeros(shape=(len(image_values), k), dtype=float) # This is for
distance from each mean
[Show More]