Path: blob/main/C3 - Unsupervised Learning, Recommenders, Reinforcement Learning/week1/C3W1A/C3W1A1/public_tests.py
3566 views
import numpy as np12def compute_centroids_test(target):3# With 3 centroids4X = np.array([[-1, -1], [-1.5, -1.5], [-1.5, 1],5[-1, 1.5], [2.5, 1.5], [-1.1, -1.7], [-1.6, 1.2]])6idx = np.array([1, 1, 1, 0, 0, 0, 2])7K = 38centroids = target(X, idx, K)9expected_centroids = np.array([[0.13333333, 0.43333333],10[-1.33333333, -0.5 ],11[-1.6, 1.2 ]])1213assert type(centroids) == np.ndarray, "Wrong type"14assert centroids.shape == (K, X.shape[1]), f"Wrong shape. Expected: {(len(X),)} got: {idx.shape}"15assert np.allclose(centroids, expected_centroids), f"Wrong values. Expected: {expected_centroids}, got: {centroids}"1617X = np.array([[2, 2.5], [2.5, 2.5], [-1.5, -1.5],18[2, 2], [-1.5, -1], [-1, -1]])19idx = np.array([0, 0, 1, 0, 1, 1])20K = 221centroids = target(X, idx, K)22expected_centroids = np.array([[[ 2.16666667, 2.33333333],23[-1.33333333, -1.16666667]]])2425assert type(centroids) == np.ndarray, "Wrong type"26assert centroids.shape == (K, X.shape[1]), f"Wrong shape. Expected: {(len(X),)} got: {idx.shape}"27assert np.allclose(centroids, expected_centroids), f"Wrong values. Expected: {expected_centroids}, got: {centroids}"2829print("\033[92mAll tests passed!")3031def find_closest_centroids_test(target):32# With 2 centroids33X = np.array([[-1, -1], [-1.5, -1.5], [-1.5, -1],34[2, 2],[2.5, 2.5],[2, 2.5]])35initial_centroids = np.array([[-1, -1], [2, 2]])36idx = target(X, initial_centroids)3738assert type(idx) == np.ndarray, "Wrong type"39assert idx.shape == (len(X),), f"Wrong shape. Expected: {(len(X),)} got: {idx.shape}"40assert np.allclose(idx, [0, 0, 0, 1, 1, 1]), "Wrong values"4142# With 3 centroids43X = np.array([[-1, -1], [-1.5, -1.5], [-1.5, 1],44[-1, 1.5], [2.5, 1.5], [2, 2]])45initial_centroids = np.array([[2.5, 2], [-1, -1], [-1.5, 1.]])46idx = target(X, initial_centroids)4748assert type(idx) == np.ndarray, "Wrong type"49assert idx.shape == (len(X),), f"Wrong shape. Expected: {(len(X),)} got: {idx.shape}"50assert np.allclose(idx, [1, 1, 2, 2, 0, 0]), f"Wrong values. Expected {[2, 2, 0, 0, 1, 1]}, got: {idx}"5152# With 3 centroids53X = np.array([[-1, -1], [-1.5, -1.5], [-1.5, 1],54[-1, 1.5], [2.5, 1.5], [-1.1, -1.7], [-1.6, 1.2]])55initial_centroids = np.array([[2.5, 2], [-1, -1], [-1.5, 1.]])56idx = target(X, initial_centroids)5758assert type(idx) == np.ndarray, "Wrong type"59assert idx.shape == (len(X),), f"Wrong shape. Expected: {(len(X),)} got: {idx.shape}"60assert np.allclose(idx, [1, 1, 2, 2, 0, 1, 2]), f"Wrong values. Expected {[2, 2, 0, 0, 1, 1]}, got: {idx}"6162print("\033[92mAll tests passed!")6364