1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# UNQ_C1
# GRADED FUNCTION: find_closest_centroids
"""
Computes the centroid memberships for every example
Args:
X (ndarray): (m, n) Input values
centroids (ndarray): (K, n) centroids
Returns:
idx (array_like): (m,) closest centroids
"""
# Set K
=
# You need to return the following variables correctly
=
### START CODE HERE ###
# Array to hold distance between X[i] and each centroids[j]
=
= # Your code to calculate the norm between (X[i] - centroids[j])
=
### END CODE HERE ###
return
# UNQ_C2
# GRADED FUNCTION: compute_centroids
"""
Returns the new centroids by computing the means of the
data points assigned to each centroid.
Args:
X (ndarray): (m, n) Data points
idx (ndarray): (m,) Array containing index of closest centroid for each
example in X. Concretely, idx[i] contains the index of
the centroid closest to example i
K (int): number of centroids
Returns:
centroids (ndarray): (K, n) New centroids computed
"""
# Useful variables
, =
# You need to return the following variables correctly
=
### START CODE HERE ###
= # Your code here to get a list of all data points in X assigned to centroid k
= # Your code here to compute the mean of the points assigned
### END CODE HERE ##
return
# You do not need to implement anything for this part
"""
Runs the K-Means algorithm on data matrix X, where each row of X
is a single example
"""
# Initialize values
, =
=
=
=
# Run K-Means
#Output progress
# For each example in X, assign it to the closest centroid
=
# Given the memberships, compute new centroids
=
return ,