Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
greyhatguy007
GitHub Repository: greyhatguy007/Machine-Learning-Specialization-Coursera
Path: blob/main/C3 - Unsupervised Learning, Recommenders, Reinforcement Learning/week1/C3W1A/C3W1A1/public_tests.py
3566 views
1
import numpy as np
2
3
def compute_centroids_test(target):
4
# With 3 centroids
5
X = np.array([[-1, -1], [-1.5, -1.5], [-1.5, 1],
6
[-1, 1.5], [2.5, 1.5], [-1.1, -1.7], [-1.6, 1.2]])
7
idx = np.array([1, 1, 1, 0, 0, 0, 2])
8
K = 3
9
centroids = target(X, idx, K)
10
expected_centroids = np.array([[0.13333333, 0.43333333],
11
[-1.33333333, -0.5 ],
12
[-1.6, 1.2 ]])
13
14
assert type(centroids) == np.ndarray, "Wrong type"
15
assert centroids.shape == (K, X.shape[1]), f"Wrong shape. Expected: {(len(X),)} got: {idx.shape}"
16
assert np.allclose(centroids, expected_centroids), f"Wrong values. Expected: {expected_centroids}, got: {centroids}"
17
18
X = np.array([[2, 2.5], [2.5, 2.5], [-1.5, -1.5],
19
[2, 2], [-1.5, -1], [-1, -1]])
20
idx = np.array([0, 0, 1, 0, 1, 1])
21
K = 2
22
centroids = target(X, idx, K)
23
expected_centroids = np.array([[[ 2.16666667, 2.33333333],
24
[-1.33333333, -1.16666667]]])
25
26
assert type(centroids) == np.ndarray, "Wrong type"
27
assert centroids.shape == (K, X.shape[1]), f"Wrong shape. Expected: {(len(X),)} got: {idx.shape}"
28
assert np.allclose(centroids, expected_centroids), f"Wrong values. Expected: {expected_centroids}, got: {centroids}"
29
30
print("\033[92mAll tests passed!")
31
32
def find_closest_centroids_test(target):
33
# With 2 centroids
34
X = np.array([[-1, -1], [-1.5, -1.5], [-1.5, -1],
35
[2, 2],[2.5, 2.5],[2, 2.5]])
36
initial_centroids = np.array([[-1, -1], [2, 2]])
37
idx = target(X, initial_centroids)
38
39
assert type(idx) == np.ndarray, "Wrong type"
40
assert idx.shape == (len(X),), f"Wrong shape. Expected: {(len(X),)} got: {idx.shape}"
41
assert np.allclose(idx, [0, 0, 0, 1, 1, 1]), "Wrong values"
42
43
# With 3 centroids
44
X = np.array([[-1, -1], [-1.5, -1.5], [-1.5, 1],
45
[-1, 1.5], [2.5, 1.5], [2, 2]])
46
initial_centroids = np.array([[2.5, 2], [-1, -1], [-1.5, 1.]])
47
idx = target(X, initial_centroids)
48
49
assert type(idx) == np.ndarray, "Wrong type"
50
assert idx.shape == (len(X),), f"Wrong shape. Expected: {(len(X),)} got: {idx.shape}"
51
assert np.allclose(idx, [1, 1, 2, 2, 0, 0]), f"Wrong values. Expected {[2, 2, 0, 0, 1, 1]}, got: {idx}"
52
53
# With 3 centroids
54
X = np.array([[-1, -1], [-1.5, -1.5], [-1.5, 1],
55
[-1, 1.5], [2.5, 1.5], [-1.1, -1.7], [-1.6, 1.2]])
56
initial_centroids = np.array([[2.5, 2], [-1, -1], [-1.5, 1.]])
57
idx = target(X, initial_centroids)
58
59
assert type(idx) == np.ndarray, "Wrong type"
60
assert idx.shape == (len(X),), f"Wrong shape. Expected: {(len(X),)} got: {idx.shape}"
61
assert np.allclose(idx, [1, 1, 2, 2, 0, 1, 2]), f"Wrong values. Expected {[2, 2, 0, 0, 1, 1]}, got: {idx}"
62
63
print("\033[92mAll tests passed!")
64