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,175 @@
|
|
|
1
|
+
# TOPIC: backward_propagation
|
|
2
|
+
# LAB: 6
|
|
3
|
+
# TITLE: Lab 6 - Backward propagation: full neural network from scratch (forward, cost, backward, update, train, predict)
|
|
4
|
+
# TAGS: backward propagation, backpropagation, neural network, gradient descent, chain rule, training, prediction
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
# ---------------- generating data ----------------
|
|
9
|
+
np.random.seed(1)
|
|
10
|
+
X = np.random.randn(2, 3)
|
|
11
|
+
print(X)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# ---------------- activation functions ----------------
|
|
15
|
+
def sigmoid(Z):
|
|
16
|
+
s = 1 / (1 + np.exp(-Z))
|
|
17
|
+
return s
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def tan(Z):
|
|
21
|
+
s = (np.exp(Z) - np.exp(-Z)) / (np.exp(Z) + np.exp(-Z))
|
|
22
|
+
return s
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
print(sigmoid(X))
|
|
26
|
+
print(tan(X))
|
|
27
|
+
|
|
28
|
+
# ---------------- input X and Y ----------------
|
|
29
|
+
np.random.seed(1)
|
|
30
|
+
X = np.random.randn(2, 3)
|
|
31
|
+
Y = (np.random.randn(1, 3) > 0)
|
|
32
|
+
print(X, X.shape)
|
|
33
|
+
print(Y)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ---------------- defining shape ----------------
|
|
37
|
+
def layer_size(X, Y, layers):
|
|
38
|
+
nx = X.shape[0]
|
|
39
|
+
nh = layers
|
|
40
|
+
ny = Y.shape[0]
|
|
41
|
+
return (nx, nh, ny)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
nx, nh, ny = layer_size(X, Y, 4)
|
|
45
|
+
print("Number of inputs (nx):", nx)
|
|
46
|
+
print("Number of neurons (nh):", nh) # neurons in the 1 hidden layer
|
|
47
|
+
print("Number of outputs (ny):", ny)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# ---------------- initializing parameters ----------------
|
|
51
|
+
def initialize_parameters(nx, nh, ny):
|
|
52
|
+
np.random.seed(2)
|
|
53
|
+
w1 = np.random.randn(nh, nx) * 0.01
|
|
54
|
+
b1 = np.zeros((nh, 1))
|
|
55
|
+
w2 = np.random.randn(ny, nh) * 0.01
|
|
56
|
+
b2 = np.zeros((ny, 1))
|
|
57
|
+
parameters = {'w1': w1, 'b1': b1, 'w2': w2, 'b2': b2}
|
|
58
|
+
return parameters
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
p = initialize_parameters(nx, nh, ny)
|
|
62
|
+
print(p)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ---------------- forward propagation ----------------
|
|
66
|
+
def forward_propagation(X, p):
|
|
67
|
+
w1 = p['w1']
|
|
68
|
+
b1 = p['b1']
|
|
69
|
+
w2 = p['w2']
|
|
70
|
+
b2 = p['b2']
|
|
71
|
+
Z1 = np.dot(w1, X) + b1
|
|
72
|
+
A1 = tan(Z1)
|
|
73
|
+
Z2 = np.dot(w2, A1) + b2
|
|
74
|
+
A2 = sigmoid(Z2)
|
|
75
|
+
cache = {'Z1': Z1, 'A1': A1, 'Z2': Z2, 'A2': A2}
|
|
76
|
+
return A2, cache
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
A2, cache = forward_propagation(X, p)
|
|
80
|
+
print(A2)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ---------------- computing cost ----------------
|
|
84
|
+
def compute_cost(A2, Y, parameters=None):
|
|
85
|
+
m = Y.shape[1]
|
|
86
|
+
# NOTE: notebook split this line in two, so the second term was dropped
|
|
87
|
+
logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y))
|
|
88
|
+
cost = -np.sum(logprobs) / m
|
|
89
|
+
cost = float(np.squeeze(cost))
|
|
90
|
+
return cost
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
print("cost:", compute_cost(A2, Y, p))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# ---------------- backward propagation ----------------
|
|
97
|
+
def BWP(parameters, cache, X, Y):
|
|
98
|
+
W1 = parameters['w1']
|
|
99
|
+
b1 = parameters['b1']
|
|
100
|
+
W2 = parameters['w2']
|
|
101
|
+
b2 = parameters['b2']
|
|
102
|
+
A1 = cache['A1']
|
|
103
|
+
A2 = cache['A2']
|
|
104
|
+
m = Y.size
|
|
105
|
+
dZ2 = A2 - Y
|
|
106
|
+
dw2 = np.dot(dZ2, A1.T) / m
|
|
107
|
+
db2 = np.sum(dZ2, axis=1, keepdims=True) / m
|
|
108
|
+
dA1 = np.dot(W2.T, dZ2)
|
|
109
|
+
dZ1 = dA1 * (1 - np.power(A1, 2)) # derivative of tanh
|
|
110
|
+
dw1 = np.dot(dZ1, X.T) / m
|
|
111
|
+
db1 = np.sum(dZ1, axis=1, keepdims=True) / m
|
|
112
|
+
grades = {'dW2': dw2, 'db2': db2, 'dW1': dw1, 'db1': db1}
|
|
113
|
+
return grades
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
grades = BWP(p, cache, X, Y)
|
|
117
|
+
print(grades)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# ---------------- updating values ----------------
|
|
121
|
+
def update(parameters, grades, lr):
|
|
122
|
+
w1 = parameters['w1']
|
|
123
|
+
b1 = parameters['b1']
|
|
124
|
+
w2 = parameters['w2']
|
|
125
|
+
b2 = parameters['b2']
|
|
126
|
+
|
|
127
|
+
dw1 = grades['dW1']
|
|
128
|
+
db1 = grades['db1']
|
|
129
|
+
dw2 = grades['dW2']
|
|
130
|
+
db2 = grades['db2']
|
|
131
|
+
|
|
132
|
+
w1 = w1 - lr * dw1
|
|
133
|
+
w2 = w2 - lr * dw2
|
|
134
|
+
b1 = b1 - lr * db1
|
|
135
|
+
b2 = b2 - lr * db2
|
|
136
|
+
|
|
137
|
+
parameters = {'w1': w1, 'b1': b1, 'w2': w2, 'b2': b2}
|
|
138
|
+
return parameters
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
parameters = update(p, grades, lr=0.01)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# ---------------- creating our own NN ----------------
|
|
145
|
+
def NN(X, Y, layers, itr=10000, print_cost=False):
|
|
146
|
+
np.random.seed(3)
|
|
147
|
+
nx, nh, ny = layer_size(X, Y, layers)
|
|
148
|
+
parameters = initialize_parameters(nx, nh, ny)
|
|
149
|
+
|
|
150
|
+
for i in range(0, itr):
|
|
151
|
+
A2, cache = forward_propagation(X, parameters)
|
|
152
|
+
cost = compute_cost(A2, Y, parameters)
|
|
153
|
+
grades = BWP(parameters, cache, X, Y)
|
|
154
|
+
parameters = update(parameters, grades, lr=0.01)
|
|
155
|
+
|
|
156
|
+
if print_cost and i % 100 == 0:
|
|
157
|
+
print("cost %i: %f" % (i, cost))
|
|
158
|
+
return parameters
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
parameters = NN(X, Y, 4, itr=1000, print_cost=True)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
# ---------------- prediction ----------------
|
|
165
|
+
def predict_dec(parameters, X):
|
|
166
|
+
# forward propagation and a classification threshold of 0.5
|
|
167
|
+
a3, cache = forward_propagation(X, parameters)
|
|
168
|
+
predictions = (a3 > 0.5)
|
|
169
|
+
return predictions
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
print(predict_dec(parameters, X))
|
|
173
|
+
|
|
174
|
+
# LAB 7: take dataset, do splitting and use tensorflow/keras
|
|
175
|
+
# one on a classification dataset and the other on a regression dataset
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# TOPIC: tensorflow_keras
|
|
2
|
+
# LAB: 7
|
|
3
|
+
# TITLE: Lab 7 - TensorFlow/Keras binary classification (California housing: high_value yes/no)
|
|
4
|
+
# TAGS: tensorflow, keras, neural network, classification, dense, dropout, sigmoid, adam, binary crossentropy
|
|
5
|
+
# NEEDS: pip install tensorflow (and the California housing CSV, or internet for the sklearn fallback)
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import pandas as pd
|
|
9
|
+
import matplotlib.pyplot as plt
|
|
10
|
+
from sklearn.model_selection import train_test_split
|
|
11
|
+
from sklearn.preprocessing import StandardScaler
|
|
12
|
+
import tensorflow as tf
|
|
13
|
+
from tensorflow import keras
|
|
14
|
+
from tensorflow.keras import layers
|
|
15
|
+
|
|
16
|
+
# ---------------- load the California Housing dataset ----------------
|
|
17
|
+
csv_path = '/content/sample_data/california_housing_train.csv' # Google Colab path
|
|
18
|
+
if os.path.exists(csv_path):
|
|
19
|
+
df_housing = pd.read_csv(csv_path)
|
|
20
|
+
else: # NOTE: fallback so it also runs elsewhere
|
|
21
|
+
from sklearn.datasets import fetch_california_housing
|
|
22
|
+
df_housing = fetch_california_housing(as_frame=True).frame.rename(
|
|
23
|
+
columns={'MedHouseVal': 'median_house_value'})
|
|
24
|
+
print(df_housing.head())
|
|
25
|
+
|
|
26
|
+
# Binary target: 1 if median_house_value is above the median, else 0
|
|
27
|
+
median_val = df_housing['median_house_value'].median()
|
|
28
|
+
df_housing['high_value'] = (df_housing['median_house_value'] > median_val).astype(int)
|
|
29
|
+
print("Median house value used for classification:", median_val)
|
|
30
|
+
|
|
31
|
+
# ---------------- data preparation ----------------
|
|
32
|
+
# remove the original median_house_value from the features (target leakage)
|
|
33
|
+
X = df_housing.drop(columns=['median_house_value', 'high_value'])
|
|
34
|
+
y = df_housing['high_value']
|
|
35
|
+
X_train, X_test, y_train, y_test = train_test_split(
|
|
36
|
+
X, y, test_size=0.2, random_state=42, stratify=y)
|
|
37
|
+
print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
|
|
38
|
+
|
|
39
|
+
scaler = StandardScaler() # scaling helps neural networks converge
|
|
40
|
+
X_train_scaled = scaler.fit_transform(X_train)
|
|
41
|
+
X_test_scaled = scaler.transform(X_test)
|
|
42
|
+
|
|
43
|
+
# ---------------- build a simple Keras binary classification model ----------------
|
|
44
|
+
model = keras.Sequential([
|
|
45
|
+
layers.Input(shape=(X_train_scaled.shape[1],)), # number of features
|
|
46
|
+
layers.Dense(64, activation='relu'),
|
|
47
|
+
layers.Dropout(0.2), # dropout for regularization
|
|
48
|
+
layers.Dense(32, activation='relu'),
|
|
49
|
+
layers.Dropout(0.2),
|
|
50
|
+
layers.Dense(1, activation='sigmoid'), # output layer for binary classification
|
|
51
|
+
])
|
|
52
|
+
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
|
|
53
|
+
model.summary()
|
|
54
|
+
|
|
55
|
+
# ---------------- train ----------------
|
|
56
|
+
history = model.fit(X_train_scaled, y_train,
|
|
57
|
+
epochs=20, # number of epochs
|
|
58
|
+
batch_size=32, # samples per gradient update
|
|
59
|
+
validation_split=0.2, # 20% of training data for validation
|
|
60
|
+
verbose=1)
|
|
61
|
+
print("\nModel training complete.")
|
|
62
|
+
|
|
63
|
+
# ---------------- evaluate on the test set ----------------
|
|
64
|
+
loss, accuracy = model.evaluate(X_test_scaled, y_test, verbose=0)
|
|
65
|
+
print(f"\nTest Loss: {loss:.4f}")
|
|
66
|
+
print(f"Test Accuracy: {accuracy:.4f}")
|
|
67
|
+
|
|
68
|
+
# ---------------- training history ----------------
|
|
69
|
+
plt.figure(figsize=(12, 5))
|
|
70
|
+
plt.subplot(1, 2, 1)
|
|
71
|
+
plt.plot(history.history['accuracy'])
|
|
72
|
+
plt.plot(history.history['val_accuracy'])
|
|
73
|
+
plt.title('Model accuracy'); plt.ylabel('Accuracy'); plt.xlabel('Epoch')
|
|
74
|
+
plt.legend(['Train', 'Validation'], loc='upper left')
|
|
75
|
+
|
|
76
|
+
plt.subplot(1, 2, 2)
|
|
77
|
+
plt.plot(history.history['loss'])
|
|
78
|
+
plt.plot(history.history['val_loss'])
|
|
79
|
+
plt.title('Model loss'); plt.ylabel('Loss'); plt.xlabel('Epoch')
|
|
80
|
+
plt.legend(['Train', 'Validation'], loc='upper left')
|
|
81
|
+
plt.tight_layout()
|
|
82
|
+
plt.show()
|
|
83
|
+
# A big gap between train and validation curves suggests overfitting;
|
|
84
|
+
# both stagnating suggests underfitting or optimal training.
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# TOPIC: pca
|
|
2
|
+
# LAB: 8
|
|
3
|
+
# TITLE: Lab 8 - PCA: from scratch (mean-centre, covariance, eigenvectors, projection), sklearn, Iris 90% variance
|
|
4
|
+
# TAGS: pca, principal component analysis, eigen, covariance, projection, explained variance, iris, dimensionality
|
|
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
|
+
from sklearn.decomposition import PCA
|
|
11
|
+
from sklearn.datasets import load_iris
|
|
12
|
+
from sklearn.preprocessing import StandardScaler
|
|
13
|
+
|
|
14
|
+
# ---------------- Step 1: get data ----------------
|
|
15
|
+
A = array([[2.5, 2.4], [0.5, 0.7], [2.2, 2.9], [1.9, 2.2], [3.1, 3],
|
|
16
|
+
[2.3, 2.7], [2, 1.6], [1, 1.1], [1.5, 1.6], [1.1, 0.9]])
|
|
17
|
+
print(A.shape)
|
|
18
|
+
|
|
19
|
+
# ---------------- Step 2: mean-centred data ----------------
|
|
20
|
+
M = mean(A.T, axis=1) # mean of each column
|
|
21
|
+
print(M)
|
|
22
|
+
C = A - M # centre columns by subtracting column means
|
|
23
|
+
print(C)
|
|
24
|
+
plt.scatter(C[:, 0], C[:, 1])
|
|
25
|
+
plt.show()
|
|
26
|
+
|
|
27
|
+
V = cov(C.T) # covariance matrix
|
|
28
|
+
print(V)
|
|
29
|
+
|
|
30
|
+
# ---------------- Step 3: eigenvalues and eigenvectors ----------------
|
|
31
|
+
eigvalues, eigvector = np.linalg.eig(V)
|
|
32
|
+
eigvalues, eigvector = np.real(eigvalues), np.real(eigvector)
|
|
33
|
+
idx = eigvalues.argsort()[::-1] # sort eigenvalues in descending order
|
|
34
|
+
eigvalues = eigvalues[idx]
|
|
35
|
+
eigvector = eigvector[:, idx]
|
|
36
|
+
eig1 = eigvector[:, :1] # first principal component
|
|
37
|
+
eig2 = eigvector[:, 1:] # remaining principal components
|
|
38
|
+
print(eigvector)
|
|
39
|
+
|
|
40
|
+
# ---------------- Step 4: projections ----------------
|
|
41
|
+
Z1 = np.dot(C, eig1) # onto the first PC
|
|
42
|
+
Z2 = np.dot(C, eig2) # onto the second PC
|
|
43
|
+
Z = np.dot(C, eigvector) # onto all PCs (rows = data points in PCA space)
|
|
44
|
+
print(Z)
|
|
45
|
+
PC1 = Z1 * eig1.T # reconstruct along each component
|
|
46
|
+
PC2 = Z2 * eig2.T
|
|
47
|
+
plt.scatter(PC1[:, 0], PC1[:, 1])
|
|
48
|
+
plt.scatter(PC2[:, 0], PC2[:, 1])
|
|
49
|
+
plt.show()
|
|
50
|
+
|
|
51
|
+
# ---------------- PCA through scikit-learn ----------------
|
|
52
|
+
pca = PCA()
|
|
53
|
+
pca.fit(A)
|
|
54
|
+
print(pca.components_.T) # each column is a principal component (eigenvector)
|
|
55
|
+
print(pca.components_.T[:, 0:1]) # first principal component
|
|
56
|
+
print(pca.explained_variance_) # eigenvalues
|
|
57
|
+
B = pca.transform(A)
|
|
58
|
+
print(B) # length of vector projection
|
|
59
|
+
print(pca.explained_variance_ / np.sum(pca.explained_variance_))
|
|
60
|
+
print(pca.explained_variance_ratio_)
|
|
61
|
+
|
|
62
|
+
# ======================================================================
|
|
63
|
+
# Experiment: PCA on the Iris dataset - how many components capture 90% variability
|
|
64
|
+
# ======================================================================
|
|
65
|
+
iris = load_iris()
|
|
66
|
+
X = iris.data
|
|
67
|
+
X_scaled = StandardScaler().fit_transform(X)
|
|
68
|
+
|
|
69
|
+
# 1. PCA on variance 90%
|
|
70
|
+
pca = PCA()
|
|
71
|
+
X_pca = pca.fit_transform(X_scaled)
|
|
72
|
+
print(pca.explained_variance_ratio_)
|
|
73
|
+
print(pca.explained_variance_ratio_.cumsum())
|
|
74
|
+
n_components = np.argmax(np.cumsum(pca.explained_variance_ratio_) >= 0.90) + 1
|
|
75
|
+
print("Number of components capturing more than 90% variability:", n_components)
|
|
76
|
+
|
|
77
|
+
# 2. PCA on only 2 components
|
|
78
|
+
pca_2 = PCA(n_components=2)
|
|
79
|
+
X_pca_2 = pca_2.fit_transform(X_scaled)
|
|
80
|
+
print("Number of components:", pca_2.n_components_)
|
|
81
|
+
print("Explained variance:", pca_2.explained_variance_ratio_)
|
|
82
|
+
print("Total variance captured:", sum(pca_2.explained_variance_ratio_) * 100, "%")
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# TOPIC: image_pca
|
|
2
|
+
# LAB: 9
|
|
3
|
+
# TITLE: Lab 9 - Image PCA: Olivetti faces (eigenfaces, reconstruction) + PCA on your own pictures
|
|
4
|
+
# TAGS: image pca, pca, eigenfaces, faces, olivetti, reconstruction, mse, explained variance, opencv
|
|
5
|
+
# NEEDS: internet on first run (Olivetti dataset); for your own pictures: pip install opencv-python and a folder "pics"
|
|
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
|
+
# =================== Part A: Olivetti faces ===================
|
|
13
|
+
faces = datasets.fetch_olivetti_faces()
|
|
14
|
+
print(faces.data.shape) # 400 -> examples, 4096 -> features (64x64 pixels)
|
|
15
|
+
|
|
16
|
+
k = faces.images[56]
|
|
17
|
+
print(k.shape) # (64, 64)
|
|
18
|
+
plt.imshow(k, cmap=plt.cm.bone)
|
|
19
|
+
plt.show()
|
|
20
|
+
|
|
21
|
+
fig = plt.figure(figsize=(8, 6)) # first 20 faces
|
|
22
|
+
for i in range(20):
|
|
23
|
+
ax = fig.add_subplot(4, 5, i + 1, xticks=[], yticks=[])
|
|
24
|
+
ax.imshow(faces.images[i], cmap=plt.cm.bone)
|
|
25
|
+
plt.show()
|
|
26
|
+
|
|
27
|
+
# PCA(100) -> 100 eigenvectors. Pass 0.9 instead to keep 90% of the variance.
|
|
28
|
+
pca = PCA(100)
|
|
29
|
+
pca.fit(faces.data) # data is centred automatically
|
|
30
|
+
|
|
31
|
+
plt.imshow(pca.mean_.reshape(faces.images[0].shape), cmap=plt.cm.bone) # average face
|
|
32
|
+
plt.title("Average face")
|
|
33
|
+
plt.show()
|
|
34
|
+
|
|
35
|
+
print(pca.components_.shape) # (100, 4096): the eigenfaces (vector v)
|
|
36
|
+
|
|
37
|
+
print(pca.explained_variance_ratio_) # variance in each PCA component
|
|
38
|
+
plt.plot(np.cumsum(pca.explained_variance_ratio_))
|
|
39
|
+
plt.xlabel("components"); plt.ylabel("cumulative variance")
|
|
40
|
+
plt.show()
|
|
41
|
+
|
|
42
|
+
# pca.components_[i] -> which component (0..99)
|
|
43
|
+
# faces.images[j].shape -> only gives the (64, 64) shape to reshape into
|
|
44
|
+
for comp in (0, 36, 99):
|
|
45
|
+
plt.imshow(pca.components_[comp].reshape(faces.images[0].shape), cmap=plt.cm.bone)
|
|
46
|
+
plt.title(f"component {comp}")
|
|
47
|
+
plt.show()
|
|
48
|
+
|
|
49
|
+
fig = plt.figure(figsize=(12, 20)) # all 100 eigenfaces (white area = where it is distinct)
|
|
50
|
+
for i in range(100):
|
|
51
|
+
ax = fig.add_subplot(20, 5, i + 1, xticks=[], yticks=[])
|
|
52
|
+
ax.imshow(pca.components_[i].reshape(faces.images[0].shape), cmap=plt.cm.bone)
|
|
53
|
+
plt.show()
|
|
54
|
+
|
|
55
|
+
# eigen space: faces_pca (omega) is saved and used for future prediction
|
|
56
|
+
faces_pca = pca.fit_transform(faces.data)
|
|
57
|
+
print(faces_pca.shape) # (400, 100)
|
|
58
|
+
# with PCA(0.9) you would get (400, ~66): fewer features, still 90% of the variance
|
|
59
|
+
|
|
60
|
+
faces_proj = pca.inverse_transform(faces_pca) # reconstruct back to the original space
|
|
61
|
+
print(faces_proj.shape) # (400, 4096)
|
|
62
|
+
plt.subplot(1, 2, 1); plt.imshow(faces_proj[0].reshape(64, 64), cmap=plt.cm.bone); plt.title("reconstructed")
|
|
63
|
+
plt.subplot(1, 2, 2); plt.imshow(faces.images[0], cmap=plt.cm.bone); plt.title("original")
|
|
64
|
+
plt.show()
|
|
65
|
+
|
|
66
|
+
# =================== Part B: your own pictures ===================
|
|
67
|
+
# Task: take 10 to 100 pictures, run PCA starting from 90% variance and keep reducing,
|
|
68
|
+
# reconstruct at each step, compare original vs reconstructed, find the MSE,
|
|
69
|
+
# and plot the explained-variance graph.
|
|
70
|
+
import os
|
|
71
|
+
import cv2
|
|
72
|
+
|
|
73
|
+
folder_path = "pics"
|
|
74
|
+
target_size = (64, 64)
|
|
75
|
+
images = []
|
|
76
|
+
for filename in sorted(os.listdir(folder_path)):
|
|
77
|
+
img = cv2.imread(os.path.join(folder_path, filename), cv2.IMREAD_GRAYSCALE)
|
|
78
|
+
if img is not None:
|
|
79
|
+
images.append(cv2.resize(img, target_size))
|
|
80
|
+
|
|
81
|
+
images = np.array(images, dtype=np.float32) / 255.0 # scale to 0-1 ONCE
|
|
82
|
+
n_samples, h, w = images.shape
|
|
83
|
+
img_flat = images.reshape(n_samples, h * w) # NOTE: notebook divided by 255 twice
|
|
84
|
+
print(f"Loaded {n_samples} images. Flattened shape: {img_flat.shape}")
|
|
85
|
+
|
|
86
|
+
fig = plt.figure(figsize=(10, 8))
|
|
87
|
+
for i in range(min(10, n_samples)):
|
|
88
|
+
ax = fig.add_subplot(3, 5, i + 1)
|
|
89
|
+
ax.imshow(images[i], cmap="gray")
|
|
90
|
+
ax.axis("off")
|
|
91
|
+
plt.show()
|
|
92
|
+
|
|
93
|
+
# keep 90% of the variance
|
|
94
|
+
pca = PCA(0.90).fit(img_flat)
|
|
95
|
+
print("Original number of features:", img_flat.shape[1])
|
|
96
|
+
print("Number of principal components:", pca.n_components_)
|
|
97
|
+
print("Explained Variance Ratio:", pca.explained_variance_ratio_)
|
|
98
|
+
|
|
99
|
+
plt.plot(np.cumsum(pca.explained_variance_ratio_))
|
|
100
|
+
plt.axhline(y=0.90, color='r', linestyle='--', label='90% Variance Threshold')
|
|
101
|
+
plt.xlabel("Number of Principal Components")
|
|
102
|
+
plt.ylabel("Cumulative Explained Variance")
|
|
103
|
+
plt.legend(); plt.title("PCA Explained Variance"); plt.grid()
|
|
104
|
+
plt.show()
|
|
105
|
+
|
|
106
|
+
images_pca = pca.transform(img_flat)
|
|
107
|
+
print("PCA transformed shape:", images_pca.shape)
|
|
108
|
+
images_reconstructed = pca.inverse_transform(images_pca)
|
|
109
|
+
|
|
110
|
+
plt.figure(figsize=(10, 4))
|
|
111
|
+
plt.subplot(1, 2, 1); plt.imshow(img_flat[0].reshape(h, w), cmap="gray"); plt.title("Original Image"); plt.axis("off")
|
|
112
|
+
plt.subplot(1, 2, 2); plt.imshow(images_reconstructed[0].reshape(h, w), cmap="gray"); plt.title("PCA Reconstructed Image"); plt.axis("off")
|
|
113
|
+
plt.show()
|
|
114
|
+
|
|
115
|
+
fig = plt.figure(figsize=(10, 8)) # what each principal component stores
|
|
116
|
+
for i in range(min(10, pca.n_components_)):
|
|
117
|
+
ax = fig.add_subplot(2, 5, i + 1)
|
|
118
|
+
ax.imshow(pca.components_[i].reshape(h, w), cmap="gray")
|
|
119
|
+
ax.set_title("PC " + str(i + 1))
|
|
120
|
+
ax.axis("off")
|
|
121
|
+
plt.show()
|
|
122
|
+
|
|
123
|
+
# how many components? try several k, compare the reconstruction MSE and variance
|
|
124
|
+
for k_ in sorted({1, 3, 8, min(n_samples, img_flat.shape[1])}):
|
|
125
|
+
p = PCA(n_components=k_).fit(img_flat)
|
|
126
|
+
r = p.inverse_transform(p.transform(img_flat))
|
|
127
|
+
print(f"k={k_:3d} MSE={np.mean((img_flat - r) ** 2):.3e} "
|
|
128
|
+
f"variance={np.sum(p.explained_variance_ratio_):.4f}")
|
|
129
|
+
# Choose the smallest k whose MSE is low and whose variance is high enough.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# TOPIC: lda
|
|
2
|
+
# LAB: 10
|
|
3
|
+
# TITLE: Lab 10 - LDA: between/within-class scatter by hand, eigen-decomposition, sklearn LDA, grand mean
|
|
4
|
+
# TAGS: lda, linear discriminant analysis, scatter matrix, within class, between class, eigen, projection
|
|
5
|
+
|
|
6
|
+
# 1. import libraries
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
import matplotlib.pyplot as plt
|
|
10
|
+
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
|
|
11
|
+
from sklearn.metrics import confusion_matrix, accuracy_score
|
|
12
|
+
|
|
13
|
+
# 2. create data
|
|
14
|
+
df = pd.DataFrame({"X1": [4, 2, 2, 3, 4, 9, 6, 9, 8, 10],
|
|
15
|
+
"X2": [1, 4, 3, 6, 4, 10, 8, 5, 7, 8],
|
|
16
|
+
"Group": [1, 1, 1, 1, 1, 2, 2, 2, 2, 2]})
|
|
17
|
+
print(df)
|
|
18
|
+
|
|
19
|
+
plt.figure(figsize=(6, 5))
|
|
20
|
+
plt.scatter(df['X1'], df['X2'], c=df['Group'], s=70)
|
|
21
|
+
plt.xlabel("X1"); plt.ylabel("X2"); plt.title("Original 2D data")
|
|
22
|
+
plt.grid()
|
|
23
|
+
plt.show()
|
|
24
|
+
|
|
25
|
+
df1 = df[df["Group"] == 1].copy()
|
|
26
|
+
df2 = df[df["Group"] == 2].copy()
|
|
27
|
+
print("Group 1\n", df1, "\n\nGroup 2\n", df2)
|
|
28
|
+
|
|
29
|
+
# 3. mean of each group
|
|
30
|
+
m1 = df1[["X1", "X2"]].mean().values
|
|
31
|
+
m2 = df2[["X1", "X2"]].mean().values
|
|
32
|
+
print("Mean of grp 1:", m1)
|
|
33
|
+
print("Mean of grp 2:", m2)
|
|
34
|
+
|
|
35
|
+
# between-class scatter matrix SB = (m1-m2)(m1-m2)^T
|
|
36
|
+
d = (m1 - m2).reshape(1, 2)
|
|
37
|
+
SB = d.T @ d
|
|
38
|
+
print("Difference of mean:", d)
|
|
39
|
+
print("Between class matrix:\n", SB)
|
|
40
|
+
|
|
41
|
+
# 4. mean-centred data
|
|
42
|
+
df1["X1_c"] = df1["X1"] - m1[0]
|
|
43
|
+
df1["X2_c"] = df1["X2"] - m1[1]
|
|
44
|
+
df2["X1_c"] = df2["X1"] - m2[0]
|
|
45
|
+
df2["X2_c"] = df2["X2"] - m2[1]
|
|
46
|
+
print(df1)
|
|
47
|
+
print(df2)
|
|
48
|
+
|
|
49
|
+
# 5. within-class scatter matrix SW = S1 + S2
|
|
50
|
+
X1c = df1[["X1_c", "X2_c"]].values
|
|
51
|
+
X2c = df2[["X1_c", "X2_c"]].values
|
|
52
|
+
S1 = X1c.T @ X1c
|
|
53
|
+
S2 = X2c.T @ X2c
|
|
54
|
+
SW = S1 + S2
|
|
55
|
+
print("S1:\n", S1, "\nS2:\n", S2, "\nWithin class matrix:\n", SW)
|
|
56
|
+
|
|
57
|
+
A = np.linalg.pinv(SW) @ SB # A = SW^-1 SB
|
|
58
|
+
print("A = SW^-1 SB:\n", A)
|
|
59
|
+
|
|
60
|
+
# 6. eigenvalues and eigenvectors -> LDA direction w
|
|
61
|
+
eigvalues, eigvectors = np.linalg.eig(A)
|
|
62
|
+
idx = np.argsort(eigvalues)[::-1]
|
|
63
|
+
eigvalues = eigvalues[idx]
|
|
64
|
+
eigvectors = eigvectors[:, idx]
|
|
65
|
+
w = np.real(eigvectors[:, 0])
|
|
66
|
+
w = w / np.linalg.norm(w)
|
|
67
|
+
print("Eigenvalues:", eigvalues)
|
|
68
|
+
print("Selected LDA direction w:", w)
|
|
69
|
+
|
|
70
|
+
# 7. scalar projections on the LDA axis
|
|
71
|
+
x = df[["X1", "X2"]].values
|
|
72
|
+
y = df["Group"].values
|
|
73
|
+
z = x @ w
|
|
74
|
+
projection_table = pd.DataFrame({"X1": df["X1"], "X2": df["X2"],
|
|
75
|
+
"Actual_Group": y, "LDA_score": z})
|
|
76
|
+
print(projection_table)
|
|
77
|
+
|
|
78
|
+
proj = z.reshape(-1, 1) * w.reshape(1, -1)
|
|
79
|
+
plt.figure(figsize=(6, 5))
|
|
80
|
+
plt.scatter(proj[:, 0], proj[:, 1], c=y, s=70)
|
|
81
|
+
plt.xlabel("Projected X1"); plt.ylabel("Projected X2")
|
|
82
|
+
plt.title("Data projected onto LDA Direction")
|
|
83
|
+
plt.grid(alpha=0.25)
|
|
84
|
+
plt.show()
|
|
85
|
+
|
|
86
|
+
# ---------------- scikit-learn LDA ----------------
|
|
87
|
+
X = df[["X1", "X2"]].values
|
|
88
|
+
y = df["Group"].values # 1D target array
|
|
89
|
+
lda = LDA(n_components=1)
|
|
90
|
+
X_lda = lda.fit_transform(X, y)
|
|
91
|
+
predict = lda.predict(X)
|
|
92
|
+
print("LDA transformed shape:", X_lda.shape)
|
|
93
|
+
print("Predictions:", predict)
|
|
94
|
+
|
|
95
|
+
# grand mean and misclassification
|
|
96
|
+
cm = confusion_matrix(y, predict)
|
|
97
|
+
acc = accuracy_score(y, predict)
|
|
98
|
+
print(cm, acc)
|
|
99
|
+
print("Grand Mean:", np.mean(X, axis=0))
|
|
100
|
+
print("Classification Rate:", acc)
|
|
101
|
+
print("Classification Rate (%):", acc * 100)
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# TOPIC: kmeans
|
|
2
|
+
# LAB: 11
|
|
3
|
+
# TITLE: Lab 11 - K-Means clustering: Wine dataset, small 2-D data, practice question (K=3)
|
|
4
|
+
# TAGS: kmeans, k-means, clustering, wine, centroids, unsupervised, standard scaler
|
|
5
|
+
# TIP: on Windows, if you see a KMeans memory-leak warning, run os.environ["OMP_NUM_THREADS"]="1" before importing sklearn
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
import matplotlib.pyplot as plt
|
|
10
|
+
from sklearn.datasets import load_wine
|
|
11
|
+
from sklearn.cluster import KMeans
|
|
12
|
+
from sklearn.preprocessing import StandardScaler
|
|
13
|
+
|
|
14
|
+
# 1. load Wine dataset
|
|
15
|
+
wine = load_wine()
|
|
16
|
+
x = pd.DataFrame(wine.data, columns=wine.feature_names)
|
|
17
|
+
print(x.head())
|
|
18
|
+
print(x.shape)
|
|
19
|
+
|
|
20
|
+
x_scaled = StandardScaler().fit_transform(x)
|
|
21
|
+
|
|
22
|
+
kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
|
|
23
|
+
kmeans.fit(x_scaled)
|
|
24
|
+
print("Cluster labels:")
|
|
25
|
+
print(kmeans.labels_)
|
|
26
|
+
print(kmeans.cluster_centers_) # cluster centroids
|
|
27
|
+
|
|
28
|
+
x['Cluster'] = kmeans.labels_
|
|
29
|
+
print(x.head())
|
|
30
|
+
print(x['Cluster'].value_counts())
|
|
31
|
+
|
|
32
|
+
plt.scatter(x['alcohol'], x['color_intensity'], c=x['Cluster'])
|
|
33
|
+
plt.xlabel("Alcohol")
|
|
34
|
+
plt.ylabel("Colour Intensity")
|
|
35
|
+
plt.title("kmeans Clustering on wine dataset")
|
|
36
|
+
plt.show()
|
|
37
|
+
|
|
38
|
+
# ---------------- small 2-D data, K = 2 ----------------
|
|
39
|
+
y = np.array([[1, 2], [1, 4], [2, 3], [2, 5], [8, 2], [8, 4], [9, 3], [9, 5]])
|
|
40
|
+
plt.scatter(y[:, 0], y[:, 1]) # plot original data
|
|
41
|
+
plt.xlabel("X1"); plt.ylabel("X2"); plt.title("OG Data")
|
|
42
|
+
plt.show()
|
|
43
|
+
|
|
44
|
+
kmeans = KMeans(n_clusters=2, random_state=42, n_init=10)
|
|
45
|
+
kmeans.fit(y)
|
|
46
|
+
print("Cluster labels:")
|
|
47
|
+
print(kmeans.labels_)
|
|
48
|
+
print(kmeans.cluster_centers_)
|
|
49
|
+
|
|
50
|
+
# ---------------- practice question: K = 3 ----------------
|
|
51
|
+
y1 = np.array([[1, 1], [1, 3], [2, 2], [2, 4], [5, 7], [6, 6],
|
|
52
|
+
[6, 8], [7, 7], [9, 1], [9, 3], [10, 2], [10, 4]])
|
|
53
|
+
kmeans1 = KMeans(n_clusters=3, random_state=42, n_init=10)
|
|
54
|
+
kmeans1.fit(y1)
|
|
55
|
+
print("Cluster labels:")
|
|
56
|
+
print(kmeans1.labels_)
|
|
57
|
+
print(kmeans1.cluster_centers_)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# TOPIC: agglomerative
|
|
2
|
+
# LAB: 12
|
|
3
|
+
# TITLE: Lab 12 - Agglomerative (hierarchical) clustering on Iris: dendrogram, linkage comparison, silhouette score
|
|
4
|
+
# TAGS: agglomerative, hierarchical, clustering, dendrogram, linkage, ward, silhouette, iris
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
from sklearn.datasets import load_iris
|
|
10
|
+
from sklearn.preprocessing import StandardScaler
|
|
11
|
+
from sklearn.cluster import AgglomerativeClustering
|
|
12
|
+
from sklearn.metrics import silhouette_score
|
|
13
|
+
from scipy.cluster.hierarchy import linkage, dendrogram
|
|
14
|
+
|
|
15
|
+
# ---------------- load dataset ----------------
|
|
16
|
+
iris = load_iris()
|
|
17
|
+
x = pd.DataFrame(iris.data, columns=iris.feature_names)
|
|
18
|
+
y = iris.target
|
|
19
|
+
print(x.shape)
|
|
20
|
+
print(x.head())
|
|
21
|
+
|
|
22
|
+
# ---------------- standardize ----------------
|
|
23
|
+
scaler = StandardScaler()
|
|
24
|
+
x_scaled = scaler.fit_transform(x)
|
|
25
|
+
|
|
26
|
+
# ---------------- dendrogram ----------------
|
|
27
|
+
z = linkage(x_scaled, method="ward")
|
|
28
|
+
plt.figure(figsize=(12, 6))
|
|
29
|
+
dendrogram(z)
|
|
30
|
+
plt.title("Agglomerative Clustering Dendrogram")
|
|
31
|
+
plt.xlabel("Observations")
|
|
32
|
+
plt.ylabel("merge Distance")
|
|
33
|
+
plt.show()
|
|
34
|
+
|
|
35
|
+
# ---------------- compare linkage methods ----------------
|
|
36
|
+
# Silhouette score: -1 to 1. Close to 1 = well clustered, close to 0 = on/near the
|
|
37
|
+
# boundary between clusters, close to -1 = probably assigned to the wrong cluster.
|
|
38
|
+
methods = ["single", "complete", "average", "ward"]
|
|
39
|
+
results = []
|
|
40
|
+
for method in methods:
|
|
41
|
+
model = AgglomerativeClustering(n_clusters=3, linkage=method)
|
|
42
|
+
labels = model.fit_predict(x_scaled)
|
|
43
|
+
score = silhouette_score(x_scaled, labels)
|
|
44
|
+
results.append([method, score])
|
|
45
|
+
print(pd.DataFrame(results, columns=["Linkage", "Silhouette Score"]))
|
|
46
|
+
|
|
47
|
+
# ---------------- Ward clustering ----------------
|
|
48
|
+
model = AgglomerativeClustering(n_clusters=3, linkage="ward")
|
|
49
|
+
labels = model.fit_predict(x_scaled)
|
|
50
|
+
|
|
51
|
+
plt.figure(figsize=(8, 6))
|
|
52
|
+
plt.scatter(x_scaled[:, 0], x_scaled[:, 1], c=labels)
|
|
53
|
+
plt.title("ward agglomerative clustering")
|
|
54
|
+
plt.xlabel("Standardized Sepal length")
|
|
55
|
+
plt.ylabel("Standardized Sepal width") # NOTE: notebook labelled both axes "Sepal length"
|
|
56
|
+
plt.show()
|
|
57
|
+
|
|
58
|
+
# ---------------- cluster vs actual classes ----------------
|
|
59
|
+
print(pd.crosstab(y, labels, rownames=["Actual Class"], colnames=["cluster"]))
|