Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jxareas
GitHub Repository: jxareas/Machine-Learning-Notebooks
Path: blob/master/1_Supervised_Machine_Learning/Week 2. Regression with multiple input variables/public_tests.py
2826 views
1
import numpy as np
2
3
4
def compute_cost_test(target):
5
# print("Using X with shape (4, 1)")
6
# Case 1
7
x = np.array([2, 4, 6, 8]).T
8
y = np.array([7, 11, 15, 19]).T
9
initial_w = 2
10
initial_b = 3.0
11
cost = target(x, y, initial_w, initial_b)
12
assert cost == 0, f"Case 1: Cost must be 0 for a perfect prediction but got {cost}"
13
14
# Case 2
15
x = np.array([2, 4, 6, 8]).T
16
y = np.array([7, 11, 15, 19]).T
17
initial_w = 2.0
18
initial_b = 1.0
19
cost = target(x, y, initial_w, initial_b)
20
assert cost == 2, f"Case 2: Cost must be 2 but got {cost}"
21
22
# print("Using X with shape (5, 1)")
23
# Case 3
24
x = np.array([1.5, 2.5, 3.5, 4.5, 1.5]).T
25
y = np.array([4, 7, 10, 13, 5]).T
26
initial_w = 1
27
initial_b = 0.0
28
cost = target(x, y, initial_w, initial_b)
29
assert np.isclose(cost, 15.325), f"Case 3: Cost must be 15.325 for a perfect prediction but got {cost}"
30
31
# Case 4
32
initial_b = 1.0
33
cost = target(x, y, initial_w, initial_b)
34
assert np.isclose(cost, 10.725), f"Case 4: Cost must be 10.725 but got {cost}"
35
36
# Case 5
37
y = y - 2
38
initial_b = 1.0
39
cost = target(x, y, initial_w, initial_b)
40
assert np.isclose(cost, 4.525), f"Case 5: Cost must be 4.525 but got {cost}"
41
42
print("\033[92mAll tests passed!")
43
44
45
def compute_gradient_test(target):
46
print("Using X with shape (4, 1)")
47
# Case 1
48
x = np.array([2, 4, 6, 8]).T
49
y = np.array([4.5, 8.5, 12.5, 16.5]).T
50
initial_w = 2.
51
initial_b = 0.5
52
dj_dw, dj_db = target(x, y, initial_w, initial_b)
53
# assert dj_dw.shape == initial_w.shape, f"Wrong shape for dj_dw. {dj_dw} != {initial_w.shape}"
54
assert dj_db == 0.0, f"Case 1: dj_db is wrong: {dj_db} != 0.0"
55
assert np.allclose(dj_dw, 0), f"Case 1: dj_dw is wrong: {dj_dw} != [[0.0]]"
56
57
# Case 2
58
x = np.array([2, 4, 6, 8]).T
59
y = np.array([4, 7, 10, 13]).T + 2
60
initial_w = 1.5
61
initial_b = 1
62
dj_dw, dj_db = target(x, y, initial_w, initial_b)
63
# assert dj_dw.shape == initial_w.shape, f"Wrong shape for dj_dw. {dj_dw} != {initial_w.shape}"
64
assert dj_db == -2, f"Case 2: dj_db is wrong: {dj_db} != -2"
65
assert np.allclose(dj_dw, -10.0), f"Case 1: dj_dw is wrong: {dj_dw} != -10.0"
66
67
print("\033[92mAll tests passed!")
68
69
70