sjlearn 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- set/__init__.py +57 -0
- set/clustering.py +136 -0
- set/codebook.py +243 -0
- set/labs_code/activation_functions.py +124 -0
- set/labs_code/lab01_numpy_basics.py +150 -0
- set/labs_code/lab02_batch_gradient_descent.py +107 -0
- set/labs_code/lab03_linear_regression.py +66 -0
- set/labs_code/lab04_logistic_regression.py +78 -0
- set/labs_code/lab05_forward_propagation.py +161 -0
- set/labs_code/lab06_backward_propagation.py +175 -0
- set/labs_code/lab07_tensorflow_keras.py +84 -0
- set/labs_code/lab08_pca.py +82 -0
- set/labs_code/lab09_image_pca.py +129 -0
- set/labs_code/lab10_lda.py +101 -0
- set/labs_code/lab11_kmeans.py +57 -0
- set/labs_code/lab12_agglomerative.py +59 -0
- set/labs_code/lab13_svm_svc.py +128 -0
- set/labs_code/lab14_concrete.py +269 -0
- set/regression.py +284 -0
- set/theory/activation_functions.md +23 -0
- set/theory/agglomerative.md +8 -0
- set/theory/backward_propagation.md +64 -0
- set/theory/batch_gradient_descent.md +63 -0
- set/theory/concrete_regression.md +8 -0
- set/theory/cross_validation.md +10 -0
- set/theory/forward_propagation.md +43 -0
- set/theory/image_pca.md +22 -0
- set/theory/kmeans.md +10 -0
- set/theory/knn.md +8 -0
- set/theory/lda.md +20 -0
- set/theory/linear_regression.md +35 -0
- set/theory/logistic_regression.md +48 -0
- set/theory/machine_learning.md +42 -0
- set/theory/neural_network.md +42 -0
- set/theory/numpy_basics.md +7 -0
- set/theory/pca.md +24 -0
- set/theory/svm.md +8 -0
- set/theory/tensorflow_keras.md +21 -0
- sjlearn-0.3.0.dist-info/METADATA +64 -0
- sjlearn-0.3.0.dist-info/RECORD +42 -0
- sjlearn-0.3.0.dist-info/WHEEL +4 -0
- sjlearn-0.3.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# TOPIC: numpy_basics
|
|
2
|
+
# LAB: 1
|
|
3
|
+
# TITLE: Lab 1 - NumPy basics: linear systems, determinant, singular matrices, broadcasting, shapes
|
|
4
|
+
# TAGS: numpy, linear equations, solve, determinant, singular, broadcasting, vectorization, dot product
|
|
5
|
+
|
|
6
|
+
import time
|
|
7
|
+
import numpy as np
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
|
|
10
|
+
a = np.array([1, 2, 3])
|
|
11
|
+
print(a)
|
|
12
|
+
|
|
13
|
+
# ---------------- 1.1 System of linear equations ----------------
|
|
14
|
+
A = np.array([[-1, 3], [3, 2]], dtype=float)
|
|
15
|
+
b = np.array([7, 1], dtype=float)
|
|
16
|
+
print("Matrix A\n", A, "\nArray b:", b)
|
|
17
|
+
print(np.shape(A), np.shape(b))
|
|
18
|
+
|
|
19
|
+
x = np.linalg.solve(A, b)
|
|
20
|
+
print("Solution:", x)
|
|
21
|
+
|
|
22
|
+
d = np.linalg.det(A)
|
|
23
|
+
print(f"Determinant of A: {d:.2f}")
|
|
24
|
+
# determinant = 0 -> no unique solution (singular)
|
|
25
|
+
# determinant != 0 -> unique solution (non-singular)
|
|
26
|
+
|
|
27
|
+
try:
|
|
28
|
+
print("Solution:\n", np.linalg.solve(A, b))
|
|
29
|
+
except np.linalg.LinAlgError as err:
|
|
30
|
+
print(err)
|
|
31
|
+
|
|
32
|
+
A_system = np.hstack((A, b.reshape((2, 1)))) # augmented matrix [A | b]
|
|
33
|
+
print(A_system)
|
|
34
|
+
print(A_system[0])
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def plot_lines(M):
|
|
38
|
+
"""Plot the two lines of a 2x2 system given the augmented matrix M."""
|
|
39
|
+
x_1 = np.linspace(-10, 10, 100)
|
|
40
|
+
x_2_line_1 = (M[0, 2] - M[0, 0] * x_1) / M[0, 1]
|
|
41
|
+
x_2_line_2 = (M[1, 2] - M[1, 0] * x_1) / M[1, 1]
|
|
42
|
+
_, ax = plt.subplots(figsize=(10, 10))
|
|
43
|
+
ax.plot(x_1, x_2_line_1, '-', linewidth=2, color='#0075ff',
|
|
44
|
+
label=f'$x_2={-M[0,0]/M[0,1]:.2f}x_1 + {M[0,2]/M[0,1]:.2f}$')
|
|
45
|
+
ax.plot(x_1, x_2_line_2, '-', linewidth=2, color='#ff7300',
|
|
46
|
+
label=f'$x_2={-M[1,0]/M[1,1]:.2f}x_1 + {M[1,2]/M[1,1]:.2f}$')
|
|
47
|
+
|
|
48
|
+
A_ = M[:, 0:-1]
|
|
49
|
+
b_ = M[:, -1::].flatten()
|
|
50
|
+
d_ = np.linalg.det(A_)
|
|
51
|
+
if d_ != 0: # unique solution -> mark it
|
|
52
|
+
solution = np.linalg.solve(A_, b_)
|
|
53
|
+
ax.plot(solution[0], solution[1], '-o', mfc='none', markersize=10,
|
|
54
|
+
markeredgecolor='#ff0000', markeredgewidth=2)
|
|
55
|
+
ax.text(solution[0] - 0.25, solution[1] + 0.75,
|
|
56
|
+
f'$({solution[0]:.0f}, {solution[1]:.0f})$', fontsize=14)
|
|
57
|
+
|
|
58
|
+
ax.tick_params(axis='x', labelsize=14)
|
|
59
|
+
ax.tick_params(axis='y', labelsize=14)
|
|
60
|
+
ax.set_xticks(np.arange(-10, 10))
|
|
61
|
+
ax.set_yticks(np.arange(-10, 10))
|
|
62
|
+
plt.xlabel('$x_1$', size=14)
|
|
63
|
+
plt.ylabel('$x_2$', size=14)
|
|
64
|
+
plt.legend(loc='upper right', fontsize=14)
|
|
65
|
+
plt.axis([-10, 10, -10, 10])
|
|
66
|
+
plt.grid()
|
|
67
|
+
plt.gca().set_aspect("equal")
|
|
68
|
+
plt.show()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
plot_lines(A_system)
|
|
72
|
+
|
|
73
|
+
# ---------------- System with no solution ----------------
|
|
74
|
+
# -x1 + 3x2 = 7
|
|
75
|
+
# 3x1 - 9x2 = 1
|
|
76
|
+
A_2 = np.array([[-1, 3], [3, -9]], dtype=float)
|
|
77
|
+
b_2 = np.array([7, 1], dtype=float)
|
|
78
|
+
print(np.shape(A_2), np.shape(b_2))
|
|
79
|
+
print(f"Determinant of A_2: {np.linalg.det(A_2):.2f}")
|
|
80
|
+
try:
|
|
81
|
+
print("Solution:\n", np.linalg.solve(A_2, b_2))
|
|
82
|
+
except np.linalg.LinAlgError as err:
|
|
83
|
+
print(err) # Singular matrix
|
|
84
|
+
A2_system = np.hstack((A_2, b_2.reshape((2, 1))))
|
|
85
|
+
print(A2_system)
|
|
86
|
+
plot_lines(A2_system)
|
|
87
|
+
|
|
88
|
+
# ---------------- Vectorisation: dot product vs for-loop ----------------
|
|
89
|
+
a = np.random.rand(1_000_000) # NOTE: notebook used 1e7; reduced so it runs fast
|
|
90
|
+
b = np.random.rand(1_000_000)
|
|
91
|
+
tic = time.time()
|
|
92
|
+
c = np.dot(a, b)
|
|
93
|
+
toc = time.time()
|
|
94
|
+
print("dot product ms:", 1000 * (toc - tic))
|
|
95
|
+
|
|
96
|
+
c = 0
|
|
97
|
+
tic = time.time()
|
|
98
|
+
for i in range(1_000_000):
|
|
99
|
+
c += a[i] * b[i]
|
|
100
|
+
toc = time.time()
|
|
101
|
+
print(c, "for-loop ms:", 1000 * (toc - tic))
|
|
102
|
+
|
|
103
|
+
# ---------------- Broadcasting ----------------
|
|
104
|
+
A = np.array([[2, 3, 5], [7, 2, 1], [4, 5, 1]])
|
|
105
|
+
print(A)
|
|
106
|
+
cal = A.sum(axis=0) # axis=0 -> sum vertically (column sums)
|
|
107
|
+
percent = 100 * (A / cal.reshape(1, 3))
|
|
108
|
+
print(percent)
|
|
109
|
+
|
|
110
|
+
B = np.array([2, 3, 4])
|
|
111
|
+
print(B * 100) # multiply with a scalar
|
|
112
|
+
print(B + 100) # add a constant
|
|
113
|
+
|
|
114
|
+
d = np.array([[2, 3, 5], [7, 2, 1], [4, 5, 1]])
|
|
115
|
+
e = np.array([10, 20, 30])
|
|
116
|
+
print(d + e) # row vector added to every row
|
|
117
|
+
|
|
118
|
+
# ---------------- Rank-1 array problem ----------------
|
|
119
|
+
a = np.random.rand(5)
|
|
120
|
+
print(a.shape, np.dot(a, a.T)) # (5,) -> a.T is the same, result is a scalar
|
|
121
|
+
|
|
122
|
+
a1 = np.random.rand(5, 1) # column vector: better for neural networks
|
|
123
|
+
print(np.dot(a1, a1.T)) # (5,5)
|
|
124
|
+
|
|
125
|
+
# ---------------- Experiment 1: shapes ----------------
|
|
126
|
+
def try_op(shape_a, shape_b, op="*"):
|
|
127
|
+
A = np.random.randint(1, 10, shape_a)
|
|
128
|
+
B = np.random.randint(1, 10, shape_b)
|
|
129
|
+
print(f"A {A.shape} {op} B {B.shape}")
|
|
130
|
+
try:
|
|
131
|
+
C = A * B if op == "*" else (A + B if op == "+" else A @ B)
|
|
132
|
+
print(" result shape:", C.shape)
|
|
133
|
+
except ValueError as err:
|
|
134
|
+
print(" ERROR:", err)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
try_op((4, 5), (4, 1)) # works
|
|
138
|
+
try_op((4, 5), (1, 5)) # works
|
|
139
|
+
try_op((4, 5), (1, 4)) # fails
|
|
140
|
+
try_op((4, 2), (2, 2)) # fails
|
|
141
|
+
try_op((4, 2), (1, 2)) # works
|
|
142
|
+
try_op((3, 4), (4,), "+") # works
|
|
143
|
+
try_op((3, 4), (3,), "+") # fails
|
|
144
|
+
try_op((4, 2), (2, 2), "@") # matrix multiplication works
|
|
145
|
+
|
|
146
|
+
# ---------------- Dot product in ML ----------------
|
|
147
|
+
X = np.array([[1, 4], [1, 6], [1, 8], [1, 12], [1, 6]])
|
|
148
|
+
w = np.array([[0.5], [0.8]])
|
|
149
|
+
print(np.dot(X, w)) # y = X.w -> (5,1)
|
|
150
|
+
print(np.dot(w.T, X.T)) # y = w.T . x.T -> (1,5) (NN style)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# TOPIC: batch_gradient_descent
|
|
2
|
+
# LAB: 2
|
|
3
|
+
# TITLE: Lab 2 - Batch gradient descent: one feature, two features, sklearn check, SGDRegressor
|
|
4
|
+
# TAGS: gradient descent, batch, learning rate, epochs, cost, sgd, linear regression
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import matplotlib.pyplot as plt
|
|
8
|
+
import sklearn.linear_model as lm
|
|
9
|
+
from sklearn.linear_model import SGDRegressor
|
|
10
|
+
|
|
11
|
+
# ---------------- STEP 1: data ----------------
|
|
12
|
+
x = np.array([0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6])
|
|
13
|
+
y = np.array([0.7, 0.65, 0.9, 0.95, 1.1, 1.115, 1.2, 1.4, 1.55, 1.5])
|
|
14
|
+
|
|
15
|
+
# ---------------- STEP 2/3: update the values ----------------
|
|
16
|
+
m = float(len(x)) # training examples
|
|
17
|
+
b0 = 0.35 # assumed values of the coefficients
|
|
18
|
+
b1 = 0.65
|
|
19
|
+
print("Known B0:", b0, " Known B1:", b1)
|
|
20
|
+
|
|
21
|
+
cost_hist = []
|
|
22
|
+
lr = 0.01
|
|
23
|
+
epochs = 100
|
|
24
|
+
for i in range(epochs):
|
|
25
|
+
h = b0 + b1 * x
|
|
26
|
+
cost = (1 / (2 * m)) * np.sum((h - y) ** 2) # NOTE: notebook had (1/2*m)*sum(h-y)**2
|
|
27
|
+
db0 = (1 / m) * np.sum(h - y) # slopes (gradients)
|
|
28
|
+
db1 = (1 / m) * np.sum((h - y) * x)
|
|
29
|
+
if i % 10 == 0:
|
|
30
|
+
print(f"cost1: {cost} \t iteration: {i}")
|
|
31
|
+
b0 = b0 - lr * db0 # new = old - lr * slope
|
|
32
|
+
b1 = b1 - lr * db1
|
|
33
|
+
cost_hist.append(cost)
|
|
34
|
+
print("\nPredicted B0:", b0)
|
|
35
|
+
print("Predicted B1:", b1)
|
|
36
|
+
|
|
37
|
+
plt.plot(np.asarray(cost_hist)) # plot the error
|
|
38
|
+
plt.title("Cost vs iteration")
|
|
39
|
+
plt.show()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# ---------------- same thing as a function ----------------
|
|
43
|
+
def LGD(x, y, lr, b0, b1, epoch, verbose=True):
|
|
44
|
+
cost_hist = []
|
|
45
|
+
m = float(len(x))
|
|
46
|
+
for i in range(epoch): # NOTE: uses the epoch argument
|
|
47
|
+
h = b0 + b1 * x
|
|
48
|
+
cost = (1 / (2 * m)) * np.sum((h - y) ** 2)
|
|
49
|
+
db0 = (1 / m) * np.sum(h - y)
|
|
50
|
+
db1 = (1 / m) * np.sum((h - y) * x)
|
|
51
|
+
if verbose and i % 10 == 0:
|
|
52
|
+
print(f"cost1: {cost} \t iteration: {i}")
|
|
53
|
+
b0 = b0 - lr * db0
|
|
54
|
+
b1 = b1 - lr * db1
|
|
55
|
+
cost_hist.append(cost)
|
|
56
|
+
return b0, b1
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
print(LGD(x, y, 0.01, 0.35, 0.65, 100))
|
|
60
|
+
|
|
61
|
+
# ---------------- cross verify with sklearn ----------------
|
|
62
|
+
reg = lm.LinearRegression()
|
|
63
|
+
reg.fit(x.reshape(-1, 1), y)
|
|
64
|
+
print("B0:", reg.intercept_, " B1:", reg.coef_)
|
|
65
|
+
|
|
66
|
+
plt.scatter(x, y, label="Data") # plot the fit line
|
|
67
|
+
plt.plot(x, b1 * x + b0, color="pink", label="Model Prediction")
|
|
68
|
+
plt.xlabel("X"); plt.ylabel("Y")
|
|
69
|
+
plt.title("Linear Regression using Gradient Descent")
|
|
70
|
+
plt.legend(); plt.grid(); plt.show()
|
|
71
|
+
|
|
72
|
+
# ---------------- Lab experiment 2: theta0, theta1, theta2 through GD ----------------
|
|
73
|
+
x1 = np.array([0.4, 0.8, 1, 1.2, 1.8, 1.8, 2, 2, 2.4, 2])
|
|
74
|
+
x2 = np.array([0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6])
|
|
75
|
+
y = np.array([0.7, 0.65, 0.9, 0.95, 1.1, 1.15, 1.2, 1.4, 1.55, 1.5])
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def LGD1(x1, x2, y, lr, b0, b1, b2, epoch, verbose=True):
|
|
79
|
+
cost_hist = []
|
|
80
|
+
m = float(len(x1)) # NOTE: notebook used len(x) (global)
|
|
81
|
+
for i in range(epoch):
|
|
82
|
+
h = b0 + b1 * x1 + b2 * x2
|
|
83
|
+
cost = (1 / (2 * m)) * np.sum((h - y) ** 2)
|
|
84
|
+
db0 = (1 / m) * np.sum(h - y)
|
|
85
|
+
db1 = (1 / m) * np.sum((h - y) * x1)
|
|
86
|
+
db2 = (1 / m) * np.sum((h - y) * x2)
|
|
87
|
+
if verbose and i % 10 == 0:
|
|
88
|
+
print(f"cost1: {cost} \t iteration: {i}")
|
|
89
|
+
b0 = b0 - lr * db0
|
|
90
|
+
b1 = b1 - lr * db1
|
|
91
|
+
b2 = b2 - lr * db2
|
|
92
|
+
cost_hist.append(cost)
|
|
93
|
+
return b0, b1, b2
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
print(LGD1(x1, x2, y, 0.01, 0.15, 0.35, 0.65, 100))
|
|
97
|
+
|
|
98
|
+
X = np.column_stack((x1, x2))
|
|
99
|
+
reg = lm.LinearRegression().fit(X, y)
|
|
100
|
+
print(reg.intercept_, reg.coef_)
|
|
101
|
+
|
|
102
|
+
sgd = SGDRegressor(loss="squared_error", learning_rate="constant", eta0=0.01,
|
|
103
|
+
max_iter=5000, tol=1e-6, random_state=42)
|
|
104
|
+
sgd.fit(X, y)
|
|
105
|
+
print("Intercept:", sgd.intercept_[0])
|
|
106
|
+
print("B1 =", sgd.coef_[0])
|
|
107
|
+
print("B2 =", sgd.coef_[1])
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# TOPIC: linear_regression
|
|
2
|
+
# LAB: 3
|
|
3
|
+
# TITLE: Lab 3 - Linear regression with gradient descent using matrices (any number of features)
|
|
4
|
+
# TAGS: linear regression, gradient descent, matrix, vectorized, multiple regression, sklearn
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import matplotlib.pyplot as plt
|
|
8
|
+
import sklearn.linear_model as lm
|
|
9
|
+
|
|
10
|
+
# ---------------- STEP 1: get data ----------------
|
|
11
|
+
np.random.seed(5)
|
|
12
|
+
x = np.array([[5, 3], [6, 4], [7, 6], [9, 8]])
|
|
13
|
+
y = np.array([2, 4, 7, 8]).reshape(-1, 1)
|
|
14
|
+
print(x.shape, y.shape)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# ---------------- STEP 2: create function (notation like neural networks) ----------------
|
|
18
|
+
def LRG(x, y, lr, epoch, verbose=True):
|
|
19
|
+
nx = x.shape[1] # no. of features
|
|
20
|
+
m = x.shape[0] # no. of observations
|
|
21
|
+
w = np.random.rand(nx, 1) # weights
|
|
22
|
+
b = 0 # bias
|
|
23
|
+
cost_hist = []
|
|
24
|
+
for i in range(epoch):
|
|
25
|
+
h = np.dot(x, w) + b
|
|
26
|
+
error = h - y
|
|
27
|
+
cost = np.dot(error.T, error) / (2 * m)
|
|
28
|
+
dw = np.dot(x.T, error) / m # slopes for w and b
|
|
29
|
+
db = np.sum(h - y) / m
|
|
30
|
+
if verbose and i % 100 == 0:
|
|
31
|
+
print(f"cost1: {cost} \t iteration: {i}")
|
|
32
|
+
w = w - lr * dw # same update formula as batch / stochastic
|
|
33
|
+
b = b - lr * db
|
|
34
|
+
cost_hist.append(cost.item())
|
|
35
|
+
return b, w, cost_hist
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
b, w, cost_hist = LRG(x, y, 0.01, 1000)
|
|
39
|
+
print(b)
|
|
40
|
+
print(w)
|
|
41
|
+
|
|
42
|
+
plt.plot(cost_hist) # error plot
|
|
43
|
+
plt.title("Cost vs iteration")
|
|
44
|
+
plt.show()
|
|
45
|
+
|
|
46
|
+
# cross verify with sklearn
|
|
47
|
+
reg = lm.LinearRegression()
|
|
48
|
+
reg.fit(x, y)
|
|
49
|
+
print("b:", reg.intercept_)
|
|
50
|
+
print("w:", reg.coef_)
|
|
51
|
+
|
|
52
|
+
# ---------------- 100 samples, 8 features ----------------
|
|
53
|
+
np.random.seed(123)
|
|
54
|
+
x1 = np.random.rand(100, 8)
|
|
55
|
+
y1 = np.random.rand(100, 1)
|
|
56
|
+
|
|
57
|
+
b1, w1, cost_hist1 = LRG(x1, y1, 0.01, 1000)
|
|
58
|
+
print(b1)
|
|
59
|
+
print(w1)
|
|
60
|
+
plt.plot(cost_hist1)
|
|
61
|
+
plt.show()
|
|
62
|
+
|
|
63
|
+
reg = lm.LinearRegression()
|
|
64
|
+
reg.fit(x1, y1)
|
|
65
|
+
print("b:", reg.intercept_)
|
|
66
|
+
print("w:", reg.coef_)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# TOPIC: logistic_regression
|
|
2
|
+
# LAB: 4
|
|
3
|
+
# TITLE: Lab 4 - Gradient descent for logistic regression (sigmoid, cost, update) vs sklearn
|
|
4
|
+
# TAGS: logistic regression, sigmoid, gradient descent, classification, cost, cross entropy
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import matplotlib.pyplot as plt
|
|
8
|
+
import sklearn.linear_model as lm
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# 1. sigmoid function
|
|
12
|
+
def sigmoid(z):
|
|
13
|
+
s = 1 / (1 + np.exp(-z))
|
|
14
|
+
return s
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# ---------------- one manual gradient-descent step ----------------
|
|
18
|
+
x1 = np.array([[1., 2., -1.], [3., 4., -3.2]])
|
|
19
|
+
y1 = np.array([[1, 0, 1]])
|
|
20
|
+
x = x1.T
|
|
21
|
+
y = y1.T
|
|
22
|
+
w = np.array([[1.2], [2.3]])
|
|
23
|
+
print(w.shape)
|
|
24
|
+
b = 2
|
|
25
|
+
nx = 2
|
|
26
|
+
m = 3
|
|
27
|
+
h = np.dot(x, w) + b
|
|
28
|
+
a = sigmoid(h)
|
|
29
|
+
error = a - y
|
|
30
|
+
cost = -(np.sum(y * np.log(a) + (1 - y) * (np.log(1 - a)))) / m
|
|
31
|
+
dw = np.dot(x.T, error) / m
|
|
32
|
+
db = np.sum(a - y) / m
|
|
33
|
+
lr = 0.009
|
|
34
|
+
w = w - lr * dw
|
|
35
|
+
b = b - lr * db
|
|
36
|
+
print("\nw:", w)
|
|
37
|
+
print("\nb:", b)
|
|
38
|
+
print("\nh:", h)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ---------------- full training function ----------------
|
|
42
|
+
def LGR(X, Y, LR, epoch, w0=None, verbose=True):
|
|
43
|
+
m = X.shape[0]
|
|
44
|
+
b = 0
|
|
45
|
+
w = np.array([[1.2], [2.3]]) if w0 is None else w0 # NOTE: uses the arguments
|
|
46
|
+
cost_hist = []
|
|
47
|
+
for i in range(epoch):
|
|
48
|
+
h = np.dot(X, w) + b
|
|
49
|
+
a = sigmoid(h)
|
|
50
|
+
error = a - Y
|
|
51
|
+
cost = -(np.sum(Y * np.log(a) + (1 - Y) * (np.log(1 - a)))) / m
|
|
52
|
+
cost_hist.append(cost.item())
|
|
53
|
+
if verbose and i % 100 == 0:
|
|
54
|
+
print(f"cost1: {cost} \t iteration: {i}")
|
|
55
|
+
dw = np.dot(X.T, error) / m
|
|
56
|
+
db = np.sum(a - Y) / m
|
|
57
|
+
w = w - LR * dw
|
|
58
|
+
b = b - LR * db
|
|
59
|
+
return b, w, cost_hist
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
x2 = np.array([[1., 3.], [2., 4.], [-1, -3.2]])
|
|
63
|
+
y2 = np.array([[1], [0], [1]])
|
|
64
|
+
|
|
65
|
+
b, w, cost_hist = LGR(x2, y2, 0.009, 1000)
|
|
66
|
+
print("weights:", w)
|
|
67
|
+
print("biases:", b)
|
|
68
|
+
print("Final cost:", cost_hist[-1])
|
|
69
|
+
|
|
70
|
+
plt.plot(np.asarray(cost_hist))
|
|
71
|
+
plt.title("Cost vs iteration")
|
|
72
|
+
plt.show()
|
|
73
|
+
|
|
74
|
+
# cross verify with sklearn (it is regularised by default, so numbers differ slightly)
|
|
75
|
+
lgr = lm.LogisticRegression()
|
|
76
|
+
lgr.fit(x2, y2.ravel())
|
|
77
|
+
print("b:", lgr.intercept_)
|
|
78
|
+
print("w:", lgr.coef_)
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# TOPIC: forward_propagation
|
|
2
|
+
# LAB: 5
|
|
3
|
+
# TITLE: Lab 5 - Forward propagation: 2-layer network and 3-layer network (4 -> 2 -> 1 neurons)
|
|
4
|
+
# TAGS: neural network, forward propagation, sigmoid, tanh, initialize parameters, cost
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def sigmoid(z):
|
|
10
|
+
s = 1 / (1 + np.exp(-z))
|
|
11
|
+
return s
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def tan(z):
|
|
15
|
+
s = (np.exp(z) - np.exp(-z)) / (np.exp(z) + np.exp(-z))
|
|
16
|
+
return s
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
np.random.seed(1)
|
|
20
|
+
x = np.random.randn(2, 3)
|
|
21
|
+
print(x)
|
|
22
|
+
print(sigmoid(x))
|
|
23
|
+
print(tan(x))
|
|
24
|
+
|
|
25
|
+
np.random.seed(1)
|
|
26
|
+
x = np.random.randn(2, 3)
|
|
27
|
+
y = (np.random.randn(1, 3) > 0)
|
|
28
|
+
print(x, x.shape)
|
|
29
|
+
print(y, y.shape)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# ---------------- layer sizes ----------------
|
|
33
|
+
def layer_sizes(x, y, layers):
|
|
34
|
+
n_x = x.shape[0]
|
|
35
|
+
n_h = layers # no. of neurons in the hidden layer
|
|
36
|
+
n_y = y.shape[0]
|
|
37
|
+
return (n_x, n_h, n_y)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
n_x, n_h, n_y = layer_sizes(x, y, 4)
|
|
41
|
+
print("no of inputs(n_x):", n_x)
|
|
42
|
+
print("no of neurons in hidden layers(n_h):", n_h)
|
|
43
|
+
print("no of outputs(n_y):", n_y)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# ---------------- initialise parameters ----------------
|
|
47
|
+
def initialize_parameters(n_x, n_h, n_y):
|
|
48
|
+
np.random.seed(2)
|
|
49
|
+
w1 = np.random.randn(n_h, n_x) * 0.01 # 1st layer
|
|
50
|
+
b1 = np.zeros((n_h, 1))
|
|
51
|
+
w2 = np.random.randn(n_y, n_h) * 0.01 # 2nd layer
|
|
52
|
+
b2 = np.zeros((n_y, 1))
|
|
53
|
+
parameters = {'W1': w1, 'b1': b1, 'W2': w2, 'b2': b2}
|
|
54
|
+
return parameters
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
p = initialize_parameters(n_x, n_h, n_y)
|
|
58
|
+
print(p)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ---------------- forward propagation ----------------
|
|
62
|
+
def forward_propagation(x, p):
|
|
63
|
+
w1 = p['W1']
|
|
64
|
+
b1 = p['b1']
|
|
65
|
+
w2 = p['W2']
|
|
66
|
+
b2 = p['b2']
|
|
67
|
+
|
|
68
|
+
z1 = np.dot(w1, x) + b1
|
|
69
|
+
A1 = tan(z1)
|
|
70
|
+
z2 = np.dot(w2, A1) + b2
|
|
71
|
+
A2 = sigmoid(z2)
|
|
72
|
+
|
|
73
|
+
cache = {'z1': z1, 'A1': A1, 'z2': z2, 'A2': A2} # to store these values
|
|
74
|
+
return A2, cache
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
A2, cache = forward_propagation(x, p)
|
|
78
|
+
print(A2)
|
|
79
|
+
print(cache)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# ---------------- cost ----------------
|
|
83
|
+
def compute_cost(A2, y, parameters=None):
|
|
84
|
+
m = y.shape[1]
|
|
85
|
+
# NOTE: notebook split this line in two, so the second term was dropped
|
|
86
|
+
logprobs = np.multiply(np.log(A2), y) + np.multiply(np.log(1 - A2), (1 - y))
|
|
87
|
+
cost = -np.sum(logprobs) / m
|
|
88
|
+
cost = float(np.squeeze(cost))
|
|
89
|
+
return cost
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
print("cost:", compute_cost(A2, y, p))
|
|
93
|
+
|
|
94
|
+
# ======================================================================
|
|
95
|
+
# Forward propagation for 5 inputs, 3 samples, 3 layers:
|
|
96
|
+
# 1st layer -> 4 neurons, 2nd layer -> 2 neurons, 3rd layer -> 1 neuron
|
|
97
|
+
# ======================================================================
|
|
98
|
+
np.random.seed(1)
|
|
99
|
+
x1 = np.random.randn(5, 3)
|
|
100
|
+
print(x1)
|
|
101
|
+
print(sigmoid(x1))
|
|
102
|
+
print(tan(x1))
|
|
103
|
+
|
|
104
|
+
y1 = (np.random.randn(1, 3) > 0) # NOTE: notebook cell had a missing bracket
|
|
105
|
+
print(y1, y1.shape)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def layer_size(x1, y1, layer1, layer2):
|
|
109
|
+
nx = x1.shape[0]
|
|
110
|
+
nh1 = layer1
|
|
111
|
+
nh2 = layer2
|
|
112
|
+
ny = y1.shape[0]
|
|
113
|
+
return (nx, nh1, nh2, ny)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
nx, nh1, nh2, ny = layer_size(x1, y1, 4, 2)
|
|
117
|
+
print("inputs:", nx, " 1st hidden:", nh1, " 2nd hidden:", nh2, " outputs:", ny)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def init_params(nx, nh1, nh2, ny):
|
|
121
|
+
np.random.seed(2)
|
|
122
|
+
w1 = np.random.randn(nh1, nx) * 0.01 # 1st layer
|
|
123
|
+
b1 = np.zeros((nh1, 1))
|
|
124
|
+
w2 = np.random.randn(nh2, nh1) * 0.01 # 2nd layer
|
|
125
|
+
b2 = np.zeros((nh2, 1))
|
|
126
|
+
w3 = np.random.randn(ny, nh2) * 0.01 # 3rd layer
|
|
127
|
+
b3 = np.zeros((ny, 1))
|
|
128
|
+
return {'W1': w1, 'b1': b1, 'W2': w2, 'b2': b2, 'W3': w3, 'b3': b3}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
p1 = init_params(nx, nh1, nh2, ny)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def forward_proptn(x1, p1):
|
|
135
|
+
w1, b1 = p1['W1'], p1['b1']
|
|
136
|
+
w2, b2 = p1['W2'], p1['b2']
|
|
137
|
+
w3, b3 = p1['W3'], p1['b3']
|
|
138
|
+
|
|
139
|
+
z1 = np.dot(w1, x1) + b1
|
|
140
|
+
A1 = tan(z1)
|
|
141
|
+
z2 = np.dot(w2, A1) + b2
|
|
142
|
+
A2 = tan(z2)
|
|
143
|
+
z3 = np.dot(w3, A2) + b3
|
|
144
|
+
A3 = sigmoid(z3)
|
|
145
|
+
|
|
146
|
+
cache = {'z1': z1, 'A1': A1, 'z2': z2, 'A2': A2, 'z3': z3, 'A3': A3}
|
|
147
|
+
return A3, cache
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
A3, cache = forward_proptn(x1, p1)
|
|
151
|
+
print(A3)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def computes_cost(A3, y1, params=None):
|
|
155
|
+
m1 = y1.shape[1]
|
|
156
|
+
logprobs = np.multiply(np.log(A3), y1) + np.multiply(np.log(1 - A3), (1 - y1))
|
|
157
|
+
cost1 = -np.sum(logprobs) / m1
|
|
158
|
+
return float(np.squeeze(cost1))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
print("cost:", computes_cost(A3, y1, p1))
|