foml-toolkit 0.2.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.
@@ -0,0 +1,63 @@
1
+ # TOPIC: logistic_gd
2
+ # LAB: 4
3
+ # TITLE: Logistic regression with gradient descent vs sklearn
4
+ # TAGS: logistic regression, sigmoid, gradient descent, classification
5
+
6
+ import numpy as np
7
+ import sklearn.linear_model as lm
8
+
9
+
10
+ def sigmoid(z):
11
+ return 1 / (1 + np.exp(-z))
12
+
13
+
14
+ # --- one manual gradient step ---
15
+ X1 = np.array([[1., 2., -1.], [3., 4., -3.2]])
16
+ Y1 = np.array([[1, 0, 1]])
17
+ X = X1.T
18
+ y = Y1.T
19
+ w = np.array([[1.2], [2.3]])
20
+ b = 2
21
+ m = 3
22
+ h = np.dot(X, w) + b
23
+ a = sigmoid(h)
24
+ error = a - y
25
+ cost = -(np.sum(y * np.log(a) + (1 - y) * np.log(1 - a))) / m
26
+ dw = np.dot(X.T, error) / m
27
+ db = np.sum(a - y) / m
28
+ lr = 0.009
29
+ w = w - lr * dw
30
+ b = b - lr * db
31
+ print(w, b, cost)
32
+
33
+
34
+ # --- full training loop ---
35
+ def LGR(X, y, lr, epochs):
36
+ nx = X.shape[1]
37
+ m = X.shape[0]
38
+ w = np.random.rand(nx, 1)
39
+ b = 0
40
+ cost1 = []
41
+ for i in range(epochs):
42
+ z = np.dot(X, w) + b
43
+ a = sigmoid(z)
44
+ cost = -(1 / m) * np.sum(y * np.log(a + 1e-15) + (1 - y) * np.log(1 - a + 1e-15))
45
+ cost1.append(cost)
46
+ error = a - y
47
+ dw = (1 / m) * np.dot(X.T, error)
48
+ db = (1 / m) * np.sum(error)
49
+ w = w - lr * dw
50
+ b = b - lr * db
51
+ return w, b, cost1
52
+
53
+
54
+ y = np.array([[1], [0], [1]])
55
+ X = np.array([[1., 3.], [2., 4.], [-1., -3.2]])
56
+ w, b, cost = LGR(X, y, 0.01, 1000)
57
+ print("W:", w)
58
+ print("B:", b)
59
+ print("Cost", cost[-1])
60
+
61
+ # --- sklearn (regularised by default, so numbers differ slightly) ---
62
+ clf = lm.LogisticRegression().fit(X, y.reshape(-1))
63
+ print(clf.intercept_, clf.coef_)
@@ -0,0 +1,88 @@
1
+ # TOPIC: nn_forward
2
+ # LAB: 5
3
+ # TITLE: Forward propagation: 2-layer and 3-layer network, activations, cost
4
+ # TAGS: neural network, forward propagation, sigmoid, tanh, cost
5
+
6
+ import numpy as np
7
+
8
+
9
+ def sigmoid(z):
10
+ return 1 / (1 + np.exp(-z))
11
+
12
+
13
+ def tan(h):
14
+ return (np.exp(h) - np.exp(-h)) / (np.exp(h) + np.exp(-h))
15
+
16
+
17
+ np.random.seed(42)
18
+ x = np.random.randn(3, 3)
19
+ print(sigmoid(x))
20
+ print(tan(x))
21
+
22
+ # ----------------------- 2-layer network (1 hidden layer) ---------------------
23
+ np.random.seed(1)
24
+ X = np.random.randn(2, 3)
25
+ Y = (np.random.randn(1, 3) > 0).astype(int)
26
+ print(X.shape, Y.shape)
27
+
28
+
29
+ def layer_sizes(X, Y, no_neurons): # NOTE: uses its arguments (not globals)
30
+ return X.shape[0], no_neurons, Y.shape[0]
31
+
32
+
33
+ def initialize_parameters(n_x, n_h, n_y):
34
+ np.random.seed(2)
35
+ return {"w1": np.random.randn(n_h, n_x) * 0.01, "b1": np.zeros((n_h, 1)),
36
+ "w2": np.random.randn(n_y, n_h) * 0.01, "b2": np.zeros((n_y, 1))}
37
+
38
+
39
+ def forward_propogation(X, p):
40
+ z1 = np.dot(p["w1"], X) + p["b1"]
41
+ a1 = tan(z1)
42
+ z2 = np.dot(p["w2"], a1) + p["b2"]
43
+ a2 = sigmoid(z2)
44
+ cache = {"a1": a1, "z1": z1, "a2": a2, "z2": z2} # NOTE: a1 (notebook stored w1)
45
+ return a2, cache
46
+
47
+
48
+ def compute_cost(a2, Y):
49
+ m = Y.shape[1]
50
+ logprobs = np.multiply(np.log(a2), Y) + np.multiply(np.log(1 - a2), (1 - Y))
51
+ return float(np.squeeze(-np.sum(logprobs) / m))
52
+
53
+
54
+ n_x, n_h, n_y = layer_sizes(X, Y, 4)
55
+ p = initialize_parameters(n_x, n_h, n_y)
56
+ a2, cache = forward_propogation(X, p)
57
+ print(a2)
58
+ print("cost:", compute_cost(a2, Y))
59
+
60
+ # ------------- 3-layer network: 5 inputs, 4 -> 2 -> 1 neurons, 3 samples ------
61
+ np.random.seed(1)
62
+ X1 = np.random.randn(5, 3)
63
+ Y1 = (np.random.randn(1, 3) > 0).astype(int)
64
+
65
+
66
+ def layer_sizes3(X1, Y1, layers1, layers2):
67
+ return X1.shape[0], layers1, layers2, Y1.shape[0]
68
+
69
+
70
+ def initialize_parameters3(n_x, n_h1, n_h2, n_y):
71
+ np.random.seed(2)
72
+ return {"w1": np.random.randn(n_h1, n_x) * 0.01, "b1": np.zeros((n_h1, 1)),
73
+ "w2": np.random.randn(n_h2, n_h1) * 0.01, "b2": np.zeros((n_h2, 1)),
74
+ "w3": np.random.randn(n_y, n_h2) * 0.01, "b3": np.zeros((n_y, 1))}
75
+
76
+
77
+ def forward_propogation3(X, p):
78
+ z1 = np.dot(p["w1"], X) + p["b1"]; a1 = tan(z1)
79
+ z2 = np.dot(p["w2"], a1) + p["b2"]; a2 = tan(z2)
80
+ z3 = np.dot(p["w3"], a2) + p["b3"]; a3 = sigmoid(z3)
81
+ return a3, {"a1": a1, "z1": z1, "a2": a2, "z2": z2, "a3": a3, "z3": z3}
82
+
83
+
84
+ n_x, n_h1, n_h2, n_y = layer_sizes3(X1, Y1, 4, 2)
85
+ p3 = initialize_parameters3(n_x, n_h1, n_h2, n_y)
86
+ a3, cache3 = forward_propogation3(X1, p3)
87
+ print(a3)
88
+ print("cost:", compute_cost(a3, Y1))
@@ -0,0 +1,96 @@
1
+ # TOPIC: nn_scratch
2
+ # LAB: 6
3
+ # TITLE: Neural network from scratch: forward, backward propagation, training, prediction
4
+ # TAGS: neural network, backpropagation, gradient descent, activation functions
5
+
6
+ import numpy as np
7
+
8
+
9
+ # Activations to know for the exam: linear, sigmoid, tanh, relu, leaky relu
10
+ def sigmoid(z):
11
+ return 1 / (1 + np.exp(-z))
12
+
13
+
14
+ def tan(z):
15
+ return (np.exp(z) - np.exp(-z)) / (np.exp(z) + np.exp(-z))
16
+
17
+
18
+ def relu(z):
19
+ return np.maximum(0, z)
20
+
21
+
22
+ def leaky_relu(z, alpha=0.01):
23
+ return np.where(z > 0, z, alpha * z)
24
+
25
+
26
+ np.random.seed(1)
27
+ X = np.random.randn(2, 3)
28
+ Y = (np.random.randn(1, 3) > 0).astype(int)
29
+
30
+
31
+ def layer_sizes(X, Y, layers):
32
+ return X.shape[0], layers, Y.shape[0]
33
+
34
+
35
+ def initialize_parameters(n_x, n_h, n_y):
36
+ np.random.seed(2)
37
+ return {'W1': np.random.randn(n_h, n_x) * 0.01, 'b1': np.zeros((n_h, 1)),
38
+ 'W2': np.random.randn(n_y, n_h) * 0.01, 'b2': np.zeros((n_y, 1))}
39
+
40
+
41
+ def forward_propogation(X, p):
42
+ z1 = np.dot(p['W1'], X) + p['b1']
43
+ A1 = tan(z1)
44
+ z2 = np.dot(p['W2'], A1) + p['b2']
45
+ A2 = sigmoid(z2)
46
+ return A2, {'z1': z1, 'A1': A1, 'z2': z2, 'A2': A2}
47
+
48
+
49
+ def compute_cost(A2, Y, parameters=None):
50
+ m = Y.shape[1]
51
+ logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y))
52
+ return float(np.squeeze(-np.sum(logprobs) / m))
53
+
54
+
55
+ def backward_propogation(parameters, cache, X, Y):
56
+ W2 = parameters["W2"]
57
+ A1, A2 = cache["A1"], cache["A2"]
58
+ m = Y.size
59
+ dZ2 = A2 - Y
60
+ dW2 = np.dot(dZ2, A1.T) / m
61
+ db2 = np.sum(dZ2, axis=1, keepdims=True) / m
62
+ dA1 = np.dot(W2.T, dZ2)
63
+ dZ1 = dA1 * (1 - np.power(A1, 2)) # derivative of tanh
64
+ dW1 = np.dot(dZ1, X.T) / m
65
+ db1 = np.sum(dZ1, axis=1, keepdims=True) / m
66
+ return {"dW2": dW2, "db2": db2, "dW1": dW1, "db1": db1}
67
+
68
+
69
+ def update(parameters, grads, lr):
70
+ return {"W1": parameters["W1"] - lr * grads["dW1"],
71
+ "b1": parameters["b1"] - lr * grads["db1"],
72
+ "W2": parameters["W2"] - lr * grads["dW2"],
73
+ "b2": parameters["b2"] - lr * grads["db2"]}
74
+
75
+
76
+ def Neural_Network(X, Y, layers, itr=10000, lr=0.01, print_cost=False):
77
+ np.random.seed(3)
78
+ n_x, n_h, n_y = layer_sizes(X, Y, layers)
79
+ parameters = initialize_parameters(n_x, n_h, n_y)
80
+ for i in range(itr):
81
+ A2, cache = forward_propogation(X, parameters)
82
+ cost = compute_cost(A2, Y)
83
+ grads = backward_propogation(parameters, cache, X, Y)
84
+ parameters = update(parameters, grads, lr)
85
+ if print_cost and i % 100 == 0:
86
+ print("Cost after iteration %i: %f" % (i, cost))
87
+ return parameters
88
+
89
+
90
+ def predict_dec(parameters, X):
91
+ A2, _ = forward_propogation(X, parameters)
92
+ return A2 > 0.5
93
+
94
+
95
+ parameters = Neural_Network(X, Y, 4, itr=1001, print_cost=True)
96
+ print(predict_dec(parameters, X)) # NOTE: use the TRAINED parameters
@@ -0,0 +1,85 @@
1
+ # TOPIC: keras_nn
2
+ # LAB: 7
3
+ # TITLE: Neural networks with TensorFlow/Keras: classification (breast cancer) + regression (diabetes)
4
+ # TAGS: tensorflow, keras, neural network, classification, regression, baseline
5
+ # NEEDS: pip install tensorflow
6
+
7
+ import numpy as np
8
+ import matplotlib.pyplot as plt
9
+ import tensorflow as tf
10
+ from tensorflow import keras
11
+ from tensorflow.keras import layers
12
+ from sklearn.datasets import load_breast_cancer, load_diabetes
13
+ from sklearn.model_selection import train_test_split
14
+ from sklearn.preprocessing import StandardScaler
15
+ from sklearn.metrics import (accuracy_score, confusion_matrix,
16
+ classification_report, r2_score, mean_squared_error)
17
+ from sklearn.dummy import DummyClassifier, DummyRegressor
18
+
19
+ np.random.seed(1)
20
+ tf.random.set_seed(1)
21
+
22
+ # ===================== Part A: classification ================================
23
+ data = load_breast_cancer()
24
+ X, Y = data.data, data.target
25
+ X_train, X_test, y_train, y_test = train_test_split(
26
+ X, Y, test_size=0.2, random_state=1, stratify=Y)
27
+ scaler = StandardScaler()
28
+ X_train = scaler.fit_transform(X_train)
29
+ X_test = scaler.transform(X_test)
30
+
31
+ clf_model = keras.Sequential([
32
+ layers.Input(shape=(X_train.shape[1],)),
33
+ layers.Dense(8, activation='relu'),
34
+ layers.Dense(4, activation='relu'),
35
+ layers.Dense(1, activation='sigmoid'), # sigmoid ONLY in the output layer
36
+ ])
37
+ clf_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
38
+ clf_model.summary()
39
+
40
+ history = clf_model.fit(X_train, y_train, validation_split=0.2,
41
+ epochs=60, batch_size=16, verbose=0)
42
+ plt.plot(history.history['loss'], label='train loss')
43
+ plt.plot(history.history['val_loss'], label='val loss')
44
+ plt.xlabel('epoch'); plt.ylabel('binary cross-entropy'); plt.legend(); plt.show()
45
+
46
+ y_prob = clf_model.predict(X_test, verbose=0).ravel()
47
+ y_pred = (y_prob > 0.5).astype(int)
48
+ test_loss, test_acc = clf_model.evaluate(X_test, y_test, verbose=0)
49
+ print("Test accuracy:", test_acc)
50
+ print(confusion_matrix(y_test, y_pred))
51
+ print(classification_report(y_test, y_pred, target_names=data.target_names))
52
+
53
+ dummy = DummyClassifier(strategy='most_frequent').fit(X_train, y_train)
54
+ print("Majority baseline:", accuracy_score(y_test, dummy.predict(X_test)))
55
+
56
+ # ===================== Part B: regression =====================================
57
+ reg_data = load_diabetes()
58
+ Xr, Yr = reg_data.data, reg_data.target
59
+ Xr_train, Xr_test, yr_train, yr_test = train_test_split(Xr, Yr, test_size=0.2, random_state=1)
60
+ scaler_r = StandardScaler()
61
+ Xr_train = scaler_r.fit_transform(Xr_train)
62
+ Xr_test = scaler_r.transform(Xr_test)
63
+ y_scaler = StandardScaler()
64
+ yr_train_s = y_scaler.fit_transform(yr_train.reshape(-1, 1)).ravel()
65
+
66
+ reg_model = keras.Sequential([
67
+ layers.Input(shape=(Xr_train.shape[1],)),
68
+ layers.Dense(16, activation='relu'),
69
+ layers.Dense(8, activation='relu'),
70
+ layers.Dense(1, activation='linear'), # linear output for regression
71
+ ])
72
+ reg_model.compile(optimizer='adam', loss='mse', metrics=['mae'])
73
+ history_r = reg_model.fit(Xr_train, yr_train_s, validation_split=0.2,
74
+ epochs=150, batch_size=16, verbose=0)
75
+
76
+ yr_pred = y_scaler.inverse_transform(
77
+ reg_model.predict(Xr_test, verbose=0).reshape(-1, 1)).ravel()
78
+ print("R2 :", r2_score(yr_test, yr_pred))
79
+ print("RMSE:", np.sqrt(mean_squared_error(yr_test, yr_pred)))
80
+ dummy_r = DummyRegressor(strategy='mean').fit(Xr_train, yr_train)
81
+ print("Mean-baseline R2:", r2_score(yr_test, dummy_r.predict(Xr_test)))
82
+
83
+ plt.scatter(yr_test, yr_pred, alpha=0.6)
84
+ lims = [min(yr_test.min(), yr_pred.min()), max(yr_test.max(), yr_pred.max())]
85
+ plt.plot(lims, lims, 'r--'); plt.xlabel('Actual'); plt.ylabel('Predicted'); plt.show()
@@ -0,0 +1,41 @@
1
+ # TOPIC: pca_manual
2
+ # LAB: 8
3
+ # TITLE: PCA from scratch with NumPy (mean-centre, covariance, eigenvectors, projection)
4
+ # TAGS: pca, eigen, covariance, principal component, projection
5
+
6
+ import numpy as np
7
+ from numpy import array, mean, cov
8
+ from numpy.linalg import eig
9
+ import matplotlib.pyplot as plt
10
+
11
+ A = array([[2.5, 2.4], [0.5, 0.7], [2.2, 2.9], [1.9, 2.2], [3.1, 3.0],
12
+ [2.3, 2.7], [2, 1.6], [1, 1.1], [1.5, 1.6], [1.1, 0.9]])
13
+ print(A.shape)
14
+
15
+ M = mean(A.T, axis=1) # column means
16
+ print(M)
17
+ C = A - M # mean-centred data
18
+ print(C)
19
+
20
+ V = cov(C.T) # covariance matrix
21
+ print(V)
22
+
23
+ eigvalues, eigvectors = eig(V)
24
+ eigvalues, eigvectors = np.real(eigvalues), np.real(eigvectors)
25
+ idx = eigvalues.argsort()[::-1] # sort descending
26
+ eigvalues = eigvalues[idx]
27
+ eigvectors = eigvectors[:, idx]
28
+ eig1 = eigvectors[:, :1] # first principal component
29
+ eig2 = eigvectors[:, 1:] # remaining component(s)
30
+ print(eigvectors)
31
+
32
+ Z1 = np.dot(C, eig1) # projections
33
+ Z2 = np.dot(C, eig2)
34
+ Z = np.dot(C, eigvectors)
35
+ print(Z)
36
+
37
+ PC1 = Z1 * eig1.T # reconstruct along each component
38
+ PC2 = Z2 * eig2.T
39
+ plt.scatter(PC1[:, 0], PC1[:, 1], label="PC1")
40
+ plt.scatter(PC2[:, 0], PC2[:, 1], label="PC2")
41
+ plt.legend(); plt.show()
@@ -0,0 +1,58 @@
1
+ # TOPIC: pca_sklearn
2
+ # LAB: 8
3
+ # TITLE: PCA with scikit-learn + choosing components (95% variance / fixed k) on Iris
4
+ # TAGS: pca, sklearn, iris, explained variance, dimensionality reduction
5
+
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ from numpy import mean, cov
9
+ from numpy.linalg import eig
10
+ from sklearn.decomposition import PCA
11
+ from sklearn.datasets import load_iris
12
+
13
+ # ---- sklearn PCA on the small matrix ----
14
+ A = np.array([[2.5, 2.4], [0.5, 0.7], [2.2, 2.9], [1.9, 2.2], [3.1, 3.0],
15
+ [2.3, 2.7], [2, 1.6], [1, 1.1], [1.5, 1.6], [1.1, 0.9]])
16
+ pca = PCA().fit(A)
17
+ print(pca.components_.T) # eigenvectors as columns (signs may differ from eig())
18
+ print(pca.components_[0]) # first principal component
19
+
20
+ # ---- Iris ----
21
+ iris = load_iris()
22
+ A = iris.data
23
+ y = iris.target # NOTE: defined here (notebook used it before defining)
24
+ print("Data shape:", A.shape)
25
+
26
+ # manual: centre -> covariance -> eig -> sort
27
+ C = A - mean(A.T, axis=1)
28
+ V = cov(C.T)
29
+ eigvalues, eigvectors = eig(V)
30
+ eigvalues, eigvectors = np.real(eigvalues), np.real(eigvectors)
31
+ idx = eigvalues.argsort()[::-1]
32
+ eigvalues, eigvectors = eigvalues[idx], eigvectors[:, idx]
33
+ print("Eigenvalues:", eigvalues)
34
+
35
+ # Method 1: keep enough components for 95% variance
36
+ ratio = eigvalues / np.sum(eigvalues)
37
+ cumulative = np.cumsum(ratio)
38
+ k_95 = np.argmax(cumulative >= 0.95) + 1
39
+ print("Components for 95%:", k_95, " variance:", cumulative[k_95 - 1])
40
+ Z_manual_95 = C @ eigvectors[:, :k_95]
41
+
42
+ pca_95 = PCA(n_components=0.95)
43
+ Z_sklearn_95 = pca_95.fit_transform(A)
44
+ print(pca_95.n_components_, pca_95.explained_variance_ratio_, Z_sklearn_95.shape)
45
+
46
+ # Method 2: fixed 2 components
47
+ Z_manual_2 = C @ eigvectors[:, :2]
48
+ pca_2 = PCA(n_components=2)
49
+ Z_sklearn_2 = pca_2.fit_transform(A)
50
+ print(pca_2.components_.shape, pca_2.explained_variance_ratio_)
51
+
52
+ # plot
53
+ plt.figure(figsize=(8, 6))
54
+ for target_id, target_name in enumerate(iris.target_names):
55
+ plt.scatter(Z_manual_2[y == target_id, 0], Z_manual_2[y == target_id, 1],
56
+ label=target_name)
57
+ plt.xlabel('Principal Component 1'); plt.ylabel('Principal Component 2')
58
+ plt.title('Iris 2-Component PCA Projection'); plt.legend(); plt.show()
@@ -0,0 +1,49 @@
1
+ # TOPIC: pca_faces
2
+ # LAB: 9
3
+ # TITLE: Image PCA on the Olivetti faces: eigenfaces, variance, reconstruction
4
+ # TAGS: pca, image, faces, eigenfaces, reconstruction, olivetti
5
+ # NEEDS: internet on first run (downloads the dataset)
6
+
7
+ import numpy as np
8
+ import matplotlib.pyplot as plt
9
+ from sklearn import datasets
10
+ from sklearn.decomposition import PCA
11
+
12
+ faces = datasets.fetch_olivetti_faces()
13
+ print(faces.data.shape) # (400, 4096): 400 images, 64x64 = 4096 features
14
+ k = faces.images[18]
15
+ print(k.shape) # (64, 64)
16
+
17
+ plt.imshow(k, cmap=plt.cm.bone); plt.show()
18
+
19
+ fig = plt.figure(figsize=(8, 6))
20
+ for i in range(18):
21
+ ax = fig.add_subplot(4, 5, i + 1, xticks=[], yticks=[])
22
+ ax.imshow(faces.images[i], cmap=plt.cm.bone)
23
+ plt.show()
24
+
25
+ # PCA: n_components=100 -> 100 eigenfaces. A float (0.9) keeps 90% variance instead.
26
+ pca = PCA(100)
27
+ pca.fit(faces.data)
28
+
29
+ plt.imshow(pca.mean_.reshape(faces.images[0].shape), cmap=plt.cm.bone) # average face
30
+ plt.title("Average face"); plt.show()
31
+ print(pca.components_.shape) # (100, 4096) eigenfaces
32
+
33
+ print(pca.explained_variance_ratio_)
34
+ plt.plot(np.cumsum(pca.explained_variance_ratio_))
35
+ plt.xlabel("components"); plt.ylabel("cumulative variance"); plt.show()
36
+
37
+ fig = plt.figure(figsize=(8, 6))
38
+ for i in range(18): # first 18 eigenfaces
39
+ ax = fig.add_subplot(4, 5, i + 1, xticks=[], yticks=[])
40
+ ax.imshow(pca.components_[i].reshape(faces.images[0].shape), cmap=plt.cm.bone)
41
+ plt.show()
42
+
43
+ # eigen space and reconstruction
44
+ faces_pca = pca.fit_transform(faces.data) # (400, 100)
45
+ print(faces_pca.shape)
46
+ faces_proj = pca.inverse_transform(faces_pca) # back to (400, 4096)
47
+ plt.subplot(1, 2, 1); plt.imshow(faces_proj[18].reshape(64, 64), cmap=plt.cm.bone); plt.title("reconstructed")
48
+ plt.subplot(1, 2, 2); plt.imshow(k, cmap=plt.cm.bone); plt.title("original")
49
+ plt.show()
@@ -0,0 +1,64 @@
1
+ # TOPIC: pca_images
2
+ # LAB: 9
3
+ # TITLE: PCA on YOUR OWN pictures: load, vary components, reconstruct, MSE, variance plot
4
+ # TAGS: pca, image, reconstruction, mse, explained variance, opencv
5
+ # NEEDS: pip install opencv-python ; put 10-100 pictures in a folder called "pics"
6
+
7
+ import os
8
+ import cv2
9
+ import numpy as np
10
+ import matplotlib.pyplot as plt
11
+ from sklearn.decomposition import PCA
12
+
13
+ folder_path = "pics"
14
+ target_size = (64, 64)
15
+ images = []
16
+ for filename in sorted(os.listdir(folder_path)):
17
+ img = cv2.imread(os.path.join(folder_path, filename), cv2.IMREAD_GRAYSCALE)
18
+ if img is not None:
19
+ images.append(cv2.resize(img, target_size))
20
+
21
+ images = np.array(images, dtype=np.float32) / 255.0 # scale to 0-1 ONCE
22
+ n_samples, h, w = images.shape
23
+ img_flat = images.reshape(n_samples, h * w) # NOTE: notebook divided by 255 twice
24
+ print(f"Loaded {n_samples} images. Flattened shape: {img_flat.shape}")
25
+
26
+ fig = plt.figure(figsize=(10, 8))
27
+ for i in range(min(10, n_samples)):
28
+ ax = fig.add_subplot(3, 5, i + 1)
29
+ ax.imshow(images[i], cmap="gray"); ax.axis("off")
30
+ plt.show()
31
+
32
+ # ---- keep 90% of the variance ----
33
+ pca = PCA(0.90).fit(img_flat)
34
+ print("Original features:", img_flat.shape[1], " components kept:", pca.n_components_)
35
+ print(pca.explained_variance_ratio_)
36
+
37
+ plt.plot(np.cumsum(pca.explained_variance_ratio_))
38
+ plt.axhline(y=0.90, color='r', linestyle='--', label='90% variance')
39
+ plt.xlabel("Number of Principal Components"); plt.ylabel("Cumulative Explained Variance")
40
+ plt.legend(); plt.grid(); plt.show()
41
+
42
+ images_pca = pca.transform(img_flat)
43
+ recon = pca.inverse_transform(images_pca)
44
+
45
+ plt.figure(figsize=(10, 4))
46
+ plt.subplot(1, 2, 1); plt.imshow(img_flat[0].reshape(h, w), cmap="gray"); plt.title("Original"); plt.axis("off")
47
+ plt.subplot(1, 2, 2); plt.imshow(recon[0].reshape(h, w), cmap="gray"); plt.title("PCA Reconstructed"); plt.axis("off")
48
+ plt.show()
49
+
50
+ fig = plt.figure(figsize=(10, 8)) # what each principal component stores
51
+ for i in range(min(10, pca.n_components_)):
52
+ ax = fig.add_subplot(2, 5, i + 1)
53
+ ax.imshow(pca.components_[i].reshape(h, w), cmap="gray")
54
+ ax.set_title("PC " + str(i + 1)); ax.axis("off")
55
+ plt.show()
56
+
57
+ # ---- how many components? sweep k, compare reconstruction MSE & variance ----
58
+ max_k = min(n_samples, img_flat.shape[1])
59
+ for k in sorted({1, 3, 8, max_k}):
60
+ p = PCA(n_components=k).fit(img_flat)
61
+ r = p.inverse_transform(p.transform(img_flat))
62
+ print(f"k={k:3d} MSE={np.mean((img_flat - r) ** 2):.3e} "
63
+ f"variance={np.sum(p.explained_variance_ratio_):.4f}")
64
+ # Pick the smallest k where the MSE is low and variance is high enough (e.g. 90%+).
@@ -0,0 +1,68 @@
1
+ # TOPIC: lda
2
+ # LAB: 10
3
+ # TITLE: Linear Discriminant Analysis: scatter matrices by hand + sklearn LDA
4
+ # TAGS: lda, discriminant, scatter matrix, within class, between class, eigen
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ import matplotlib.pyplot as plt
9
+ from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
10
+ from sklearn.metrics import confusion_matrix, accuracy_score
11
+
12
+ df = pd.DataFrame({
13
+ "X1": [4, 2, 2, 3, 4, 9, 6, 9, 8, 10],
14
+ "X2": [1, 4, 3, 6, 4, 10, 8, 5, 7, 8],
15
+ "Group": [1, 1, 1, 1, 1, 2, 2, 2, 2, 2],
16
+ })
17
+ plt.figure(figsize=(6, 5))
18
+ plt.scatter(df["X1"], df["X2"], c=df["Group"], s=70)
19
+ plt.grid(True); plt.show()
20
+
21
+ df1 = df[df["Group"] == 1].copy()
22
+ df2 = df[df["Group"] == 2].copy()
23
+ mu1 = df1[["X1", "X2"]].mean().values
24
+ mu2 = df2[["X1", "X2"]].mean().values
25
+ print(mu1, mu2)
26
+
27
+ # between-class scatter
28
+ d = (mu1 - mu2).reshape(1, 2)
29
+ sb = d.T @ d
30
+ print(sb)
31
+
32
+ # within-class scatter
33
+ df1["x1_c"] = df1["X1"] - mu1[0]
34
+ df1["x2_c"] = df1["X2"] - mu1[1]
35
+ df2["x1_c"] = df2["X1"] - mu2[0]
36
+ df2["x2_c"] = df2["X2"] - mu2[1] # NOTE: notebook used df2["X1"] here (typo)
37
+ x1c = df1[["x1_c", "x2_c"]].values
38
+ x2c = df2[["x1_c", "x2_c"]].values
39
+ s1 = x1c.T @ x1c
40
+ s2 = x2c.T @ x2c
41
+ sw = s1 + s2
42
+ print(s1, s2, sw)
43
+
44
+ # eigen-decomposition of pinv(Sw) @ Sb -> discriminant direction w
45
+ a = np.linalg.pinv(sw) @ sb
46
+ eigvalues, eigvectors = np.linalg.eig(a)
47
+ idx = np.argsort(eigvalues)[::-1]
48
+ eigvalues, eigvectors = eigvalues[idx], eigvectors[:, idx]
49
+ w = np.real(eigvectors[:, 0])
50
+ w = w / np.linalg.norm(w)
51
+ print(eigvalues, w)
52
+
53
+ X = df[["X1", "X2"]].values
54
+ y = df["Group"].values
55
+ z = X @ w # LDA scores (1-D projection)
56
+ print(pd.DataFrame({"X1": df["X1"], "X2": df["X2"], "Actual Group": y, "LDA Score": z}))
57
+
58
+ proj = z.reshape(-1, 1) * w.reshape(1, -1)
59
+ plt.figure(figsize=(6, 5)); plt.scatter(proj[:, 0], proj[:, 1], c=y, s=70); plt.show()
60
+
61
+ # ---- sklearn ----
62
+ lda = LinearDiscriminantAnalysis(n_components=1)
63
+ X_lda = lda.fit_transform(X, y)
64
+ predict = lda.predict(X)
65
+ print(X_lda.shape, predict)
66
+ print(confusion_matrix(y, predict), accuracy_score(y, predict))
67
+ print("Grand mean:", np.mean(X, axis=0))
68
+ print("Classification rate (%):", accuracy_score(y, predict) * 100)
@@ -0,0 +1,43 @@
1
+ # TOPIC: kmeans
2
+ # LAB: 11
3
+ # TITLE: K-Means clustering: Wine dataset, small 2-D data, practice question (K=3)
4
+ # TAGS: kmeans, k-means, clustering, wine, centroids, unsupervised
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ import matplotlib.pyplot as plt
9
+ from sklearn.cluster import KMeans
10
+ from sklearn.datasets import load_wine
11
+ from sklearn.preprocessing import StandardScaler
12
+
13
+ # ---- Wine ----
14
+ wine = load_wine()
15
+ X = pd.DataFrame(wine.data, columns=wine.feature_names)
16
+ print(X.head()); print("Dataset shape:", X.shape)
17
+
18
+ X_scaled = StandardScaler().fit_transform(X)
19
+ kmeans = KMeans(n_clusters=3, random_state=42, n_init=10).fit(X_scaled)
20
+ print("Cluster Labels:", kmeans.labels_)
21
+ print("Cluster Centroids:", kmeans.cluster_centers_)
22
+
23
+ X['Cluster'] = kmeans.labels_
24
+ print(X['Cluster'].value_counts())
25
+
26
+ plt.scatter(X['alcohol'], X['color_intensity'], c=X['Cluster'], cmap='plasma')
27
+ plt.xlabel('Alcohol'); plt.ylabel('Color Intensity')
28
+ plt.title('K-Means Clustering of Wine Dataset'); plt.show()
29
+
30
+ # ---- small 2-D data, K=2 ----
31
+ X = np.array([[1, 2], [1, 4], [2, 3], [2, 5], [8, 2], [8, 4], [9, 3], [9, 5]])
32
+ plt.scatter(X[:, 0], X[:, 1]); plt.title('Original Data'); plt.show()
33
+ kmeans2 = KMeans(n_clusters=2, random_state=42, n_init=10).fit(X)
34
+ print(kmeans2.labels_); print(kmeans2.cluster_centers_)
35
+ plt.scatter(X[:, 0], X[:, 1], c=kmeans2.labels_)
36
+ plt.title('Data after K-Means Clustering'); plt.show()
37
+
38
+ # ---- Practice question: K = 3 ----
39
+ X2 = np.array([[1,1],[1,3],[2,2],[2,4],[5,7],[6,6],[6,8],[7,7],[9,1],[9,3],[10,2],[10,4]])
40
+ kmeans3 = KMeans(n_clusters=3, random_state=42, n_init=10).fit(X2)
41
+ print(kmeans3.labels_); print(kmeans3.cluster_centers_)
42
+ plt.scatter(X2[:, 0], X2[:, 1], c=kmeans3.labels_)
43
+ plt.title('Data after K-Means Clustering'); plt.show()