-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
42 lines (28 loc) · 848 Bytes
/
utils.py
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
import numpy as np
def compute_error(x, y, m):
x = np.array(x)
y = np.array(y)
m = np.float64(m)
assert len(x) == len(y)
assert len(x) != 0
return (np.linalg.norm(y - m * x) ** 2) / (2 * len(x))
def compute_error_gradient(x, y, m):
x = np.array(x)
y = np.array(y)
m = np.float64(m)
assert len(x) == len(y)
assert len(x) != 0
return ((m * (x @ x)) - (x @ y)) / len(x)
if __name__ == "__main__":
data = np.genfromtxt('data.txt')
x = data[:, 0].copy()
y = data[:, 1].copy()
ms = np.arange(0, 6, 0.1)
errors = []
grads = []
for m in ms:
errors.append(compute_error(x, y, m))
grads.append(compute_error_gradient(x, y, m))
errors = np.array(errors)
grads = np.array(grads)
np.savetxt('errors.txt', np.column_stack([ms, errors, grads]))