fomltools 0.1.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.
- fomltools/__init__.py +10 -0
- fomltools/labs/__init__.py +5 -0
- fomltools/labs/lab01.py +210 -0
- fomltools/labs/lab02.py +233 -0
- fomltools/labs/lab03.py +62 -0
- fomltools/labs/lab04.py +81 -0
- fomltools/labs/lab05.py +171 -0
- fomltools/labs/lab06.py +174 -0
- fomltools/labs/lab07.py +192 -0
- fomltools/labs/lab08.py +202 -0
- fomltools/labs/lab09.py +335 -0
- fomltools/labs/lab10.py +111 -0
- fomltools/labs/lab11.py +103 -0
- fomltools/labs/lab12.py +68 -0
- fomltools/labs/lab14.py +251 -0
- fomltools-0.1.0.dist-info/METADATA +43 -0
- fomltools-0.1.0.dist-info/RECORD +20 -0
- fomltools-0.1.0.dist-info/WHEEL +5 -0
- fomltools-0.1.0.dist-info/licenses/LICENSE +21 -0
- fomltools-0.1.0.dist-info/top_level.txt +1 -0
fomltools/labs/lab08.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""Lab 8 code imported from the uploaded FOML notebook."""
|
|
2
|
+
|
|
3
|
+
def run():
|
|
4
|
+
"""Run the original lab code in notebook-cell order."""
|
|
5
|
+
import numpy as np
|
|
6
|
+
from numpy import array, mean, cov
|
|
7
|
+
from numpy.linalg import eig
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
|
|
10
|
+
# Define a matrix
|
|
11
|
+
A = array([[2.5,2.4],[0.5,0.7],[2.2,2.9],[1.9,2.2],[3.1,3.0],[2.3,2.7],[2,1.6],[1,1.1],[1.5,1.6],[1.1,0.9]])
|
|
12
|
+
print(A.shape)
|
|
13
|
+
|
|
14
|
+
# Calculating the mea of each column
|
|
15
|
+
M = mean(A.T, axis=1)
|
|
16
|
+
print(M)
|
|
17
|
+
|
|
18
|
+
# Make columns mean-centred by subtracting column means
|
|
19
|
+
C = A - M
|
|
20
|
+
print(C)
|
|
21
|
+
|
|
22
|
+
# Calculate covariance matrix of centered matrix
|
|
23
|
+
V = cov(C.T)
|
|
24
|
+
print(V)
|
|
25
|
+
|
|
26
|
+
# calculate eigenvector (V) for projection
|
|
27
|
+
|
|
28
|
+
# Calculate eigenvalues and eigenvectors of the covariance matrix(V)
|
|
29
|
+
eigvalues, eigvectors = eig(V)
|
|
30
|
+
|
|
31
|
+
# Pick the highest eigenvector
|
|
32
|
+
# Sort eigenvalues in descending order and get the indices
|
|
33
|
+
idx = eigvalues.argsort()[::-1]
|
|
34
|
+
|
|
35
|
+
# Reorder the eigenvalues and eigenvectors according on sorted indices
|
|
36
|
+
eigvalues = eigvalues[idx]
|
|
37
|
+
eigvectors = eigvectors[:,idx]
|
|
38
|
+
|
|
39
|
+
#Extract the first principal component (eigenvector corresponding to the largest eigenvalue)
|
|
40
|
+
eig1 = eigvectors[:,:1]
|
|
41
|
+
|
|
42
|
+
# Extract the remaining principal components (eigenvectors after the first)
|
|
43
|
+
eig2 = eigvectors[:,1:]
|
|
44
|
+
|
|
45
|
+
print(eigvectors)
|
|
46
|
+
|
|
47
|
+
# Project the centred data onto the first principal component
|
|
48
|
+
Z1 = np.dot(C,eig1)
|
|
49
|
+
# Project the centred data onto the second principal component
|
|
50
|
+
Z2 = np.dot(C,eig2)
|
|
51
|
+
# Project the centred data onto all principal components
|
|
52
|
+
Z = np.dot(C,eigvectors)
|
|
53
|
+
# Print the transformed data matrix Z, where each row represents a data point
|
|
54
|
+
print(Z)
|
|
55
|
+
# Reconstruct the data along the first principal component
|
|
56
|
+
PC1 = Z1 * eig1.T
|
|
57
|
+
# Reconstruct the data along the second principal component
|
|
58
|
+
PC2 = Z2 * eig2.T
|
|
59
|
+
# Scatter plot for the projections of the data along the first principal component
|
|
60
|
+
plt.scatter(PC1[:,0], PC1[:,1])
|
|
61
|
+
# Scatter plot for the projections of the data along the second principal component
|
|
62
|
+
plt.scatter(PC2[:,0], PC2[:,1])
|
|
63
|
+
|
|
64
|
+
# PCA through Numpy and Scikit-learn
|
|
65
|
+
|
|
66
|
+
# Importing necessary libraries
|
|
67
|
+
import numpy as np
|
|
68
|
+
from sklearn.decomposition import PCA
|
|
69
|
+
|
|
70
|
+
# Initiate the PCA object
|
|
71
|
+
pca = PCA()
|
|
72
|
+
|
|
73
|
+
# Fit the PCA model on the data matrix A
|
|
74
|
+
pca.fit(A)
|
|
75
|
+
|
|
76
|
+
# Access the principal compoents (eigenvectors)
|
|
77
|
+
# Each column corresponds to a principal component
|
|
78
|
+
print(pca.components_.T) # Transpose to have eigenvectors as columns
|
|
79
|
+
|
|
80
|
+
# Acess the first principal component (eigenvector corresponding to the largest eigenvalue)
|
|
81
|
+
print(pca.components_[0]) # Extract the first column (first principal component)
|
|
82
|
+
|
|
83
|
+
# Importing Iris dataset
|
|
84
|
+
from sklearn.datasets import load_iris
|
|
85
|
+
from sklearn.preprocessing import StandardScaler
|
|
86
|
+
|
|
87
|
+
iris = load_iris()
|
|
88
|
+
A = iris.data
|
|
89
|
+
print("Data shape:", X.shape)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
import numpy as np
|
|
93
|
+
from numpy import array, mean, cov
|
|
94
|
+
from numpy.linalg import eig
|
|
95
|
+
from sklearn.datasets import load_iris
|
|
96
|
+
from sklearn.decomposition import PCA
|
|
97
|
+
|
|
98
|
+
# Calculating the mean of each column
|
|
99
|
+
M = mean(A.T, axis=1)
|
|
100
|
+
|
|
101
|
+
# Make columns mean-centred by subtracting column means
|
|
102
|
+
C = A - M
|
|
103
|
+
|
|
104
|
+
# Calculate covariance matrix of centered matrix
|
|
105
|
+
V = cov(C.T)
|
|
106
|
+
|
|
107
|
+
# Calculate eigenvalues and eigenvectors of the covariance matrix(V)
|
|
108
|
+
eigvalues, eigvectors = eig(V)
|
|
109
|
+
|
|
110
|
+
# Sort eigenvalues in descending order and get the indices
|
|
111
|
+
idx = eigvalues.argsort()[::-1]
|
|
112
|
+
|
|
113
|
+
# Reorder the eigenvalues and eigenvectors according to sorted indices
|
|
114
|
+
eigvalues = eigvalues[idx]
|
|
115
|
+
eigvectors = eigvectors[:, idx]
|
|
116
|
+
|
|
117
|
+
print("Eigenvalues:\n", eigvalues)
|
|
118
|
+
print("Eigenvectors:\n", eigvectors)
|
|
119
|
+
|
|
120
|
+
# Compute explained variance ratio and cumulative sum
|
|
121
|
+
explained_variance_ratio = eigvalues / np.sum(eigvalues)
|
|
122
|
+
cumulative_variance = np.cumsum(explained_variance_ratio)
|
|
123
|
+
|
|
124
|
+
# Find minimum components needed to reach >= 95% variance
|
|
125
|
+
k_95 = np.argmax(cumulative_variance >= 0.95) + 1
|
|
126
|
+
print(f"Number of components selected (Manual 95%): {k_95}")
|
|
127
|
+
print(f"Cumulative variance captured: {cumulative_variance[k_95 - 1]:.4f}")
|
|
128
|
+
|
|
129
|
+
# Extract top k eigenvectors
|
|
130
|
+
eig_95 = eigvectors[:, :k_95]
|
|
131
|
+
|
|
132
|
+
# Project the centred data onto the selected principal components
|
|
133
|
+
Z_manual_95 = np.dot(C, eig_95)
|
|
134
|
+
print("Manual Transformed shape (95%):", Z_manual_95.shape)
|
|
135
|
+
|
|
136
|
+
# Using in-built PCA
|
|
137
|
+
# Initiate and fit PCA with 0.95 variance ratio
|
|
138
|
+
pca_95 = PCA(n_components=0.95)
|
|
139
|
+
Z_sklearn_95 = pca_95.fit_transform(A)
|
|
140
|
+
|
|
141
|
+
print(f"Number of components selected (In-built 95%): {pca_95.n_components_}")
|
|
142
|
+
print("Explained variance ratio:", pca_95.explained_variance_ratio_)
|
|
143
|
+
print("In-built Transformed shape (95%):", Z_sklearn_95.shape)
|
|
144
|
+
|
|
145
|
+
# Extract the first principal component
|
|
146
|
+
eig1 = eigvectors[:, :1]
|
|
147
|
+
|
|
148
|
+
# Extract the second principal component
|
|
149
|
+
eig2 = eigvectors[:, 1:2]
|
|
150
|
+
|
|
151
|
+
# Project the centred data onto the first two principal components
|
|
152
|
+
eig_2comp = eigvectors[:, :2]
|
|
153
|
+
Z_manual_2 = np.dot(C, eig_2comp)
|
|
154
|
+
|
|
155
|
+
# Projections onto individual components
|
|
156
|
+
Z1 = np.dot(C, eig1)
|
|
157
|
+
Z2 = np.dot(C, eig2)
|
|
158
|
+
|
|
159
|
+
print("Manual Transformed shape (2 components):", Z_manual_2.shape)
|
|
160
|
+
|
|
161
|
+
# Initiate and fit PCA with fixed 2 components
|
|
162
|
+
pca_2 = PCA(n_components=2)
|
|
163
|
+
Z_sklearn_2 = pca_2.fit_transform(A)
|
|
164
|
+
|
|
165
|
+
print("In-built Components shape:", pca_2.components_.shape)
|
|
166
|
+
print("In-built Transformed shape (2 components):", Z_sklearn_2.shape)
|
|
167
|
+
print("Explained variance ratio:", pca_2.explained_variance_ratio_)
|
|
168
|
+
|
|
169
|
+
import matplotlib.pyplot as plt
|
|
170
|
+
|
|
171
|
+
# Reconstruct data along the first principal component
|
|
172
|
+
PC1 = Z1 * eig1.T
|
|
173
|
+
|
|
174
|
+
# Reconstruct data along the second principal component
|
|
175
|
+
PC2 = Z2 * eig2.T
|
|
176
|
+
|
|
177
|
+
# Scatter plot for the projections of the data along the first principal component
|
|
178
|
+
plt.scatter(PC1[:, 0], PC1[:, 1], label='PC1 Projection')
|
|
179
|
+
|
|
180
|
+
# Scatter plot for the projections of the data along the second principal component
|
|
181
|
+
plt.scatter(PC2[:, 0], PC2[:, 1], label='PC2 Projection')
|
|
182
|
+
|
|
183
|
+
plt.xlabel('Feature 1 (Centered)')
|
|
184
|
+
plt.ylabel('Feature 2 (Centered)')
|
|
185
|
+
plt.title('Projections along PC1 and PC2')
|
|
186
|
+
plt.legend()
|
|
187
|
+
plt.show()
|
|
188
|
+
|
|
189
|
+
plt.figure(figsize=(8, 6))
|
|
190
|
+
|
|
191
|
+
for target_id, target_name in enumerate(iris.target_names):
|
|
192
|
+
plt.scatter(
|
|
193
|
+
Z_manual_2[y == target_id, 0],
|
|
194
|
+
Z_manual_2[y == target_id, 1],
|
|
195
|
+
label=target_name
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
plt.xlabel('Principal Component 1')
|
|
199
|
+
plt.ylabel('Principal Component 2')
|
|
200
|
+
plt.title('Iris 2-Component PCA Projection')
|
|
201
|
+
plt.legend()
|
|
202
|
+
plt.show()
|
fomltools/labs/lab09.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
"""Lab 9 code imported from the uploaded FOML notebook."""
|
|
2
|
+
|
|
3
|
+
def run():
|
|
4
|
+
"""Run the original lab code in notebook-cell order."""
|
|
5
|
+
# import dependencies
|
|
6
|
+
from sklearn import datasets
|
|
7
|
+
faces = datasets.fetch_olivetti_faces()
|
|
8
|
+
faces.data.shape
|
|
9
|
+
|
|
10
|
+
# Flattening the images
|
|
11
|
+
k = faces.images[18]
|
|
12
|
+
k.shape
|
|
13
|
+
|
|
14
|
+
faces
|
|
15
|
+
# when we print faces it basically prints the vector space of all the images in the dataset. It is a 2D array of shape (400, 64, 64) where 400 is the number of images and 64x64 is the size of each image. Each image is represented as a 2D array of pixel values.
|
|
16
|
+
|
|
17
|
+
# plotting/visualizing the images
|
|
18
|
+
import matplotlib.pyplot as plt
|
|
19
|
+
plt.imshow(k, cmap=plt.cm.bone)
|
|
20
|
+
|
|
21
|
+
fig = plt.figure(figsize=(8, 6))
|
|
22
|
+
for i in range(18):
|
|
23
|
+
ax = fig.add_subplot(4, 5, i + 1, xticks=[], yticks=[])
|
|
24
|
+
ax.imshow(faces.images[i], cmap=plt.cm.bone)
|
|
25
|
+
|
|
26
|
+
faces.data
|
|
27
|
+
|
|
28
|
+
# Performing PCA
|
|
29
|
+
from sklearn.decomposition import PCA
|
|
30
|
+
pca = PCA(100) # blank => all para to show in the visualization, or else give some percentage/number of components to show
|
|
31
|
+
# if passed 0.9 ==> 90% of var
|
|
32
|
+
# 100 means 100 eigen vectors
|
|
33
|
+
|
|
34
|
+
# fit data
|
|
35
|
+
pca.fit(faces.data) # automatically converted to 0,0 axis ==> pass original data
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# jitne number of images hai utne components banenge after PCA
|
|
39
|
+
|
|
40
|
+
plt.imshow(pca.mean_.reshape(faces.images[0].shape), cmap=plt.cm.bone)
|
|
41
|
+
|
|
42
|
+
print(pca.components_.shape) # vector v
|
|
43
|
+
|
|
44
|
+
import numpy as np
|
|
45
|
+
# print(pca.explained_variance_/np.sum(pca.explained_variance_))
|
|
46
|
+
|
|
47
|
+
print(pca.explained_variance_ratio_) # how much variance is explained by each component
|
|
48
|
+
plt.plot(np.cumsum(pca.explained_variance_ratio_)) # cumulative sum of explained variance ratio
|
|
49
|
+
|
|
50
|
+
pca.components_[0] # shows the first principle component
|
|
51
|
+
|
|
52
|
+
plt.imshow(pca.components_[0].reshape(faces.images[0].shape), cmap=plt.cm.bone)
|
|
53
|
+
|
|
54
|
+
plt.imshow(pca.components_[0].reshape(faces.images[1].shape), cmap=plt.cm.bone)
|
|
55
|
+
|
|
56
|
+
plt.imshow(pca.components_[0].reshape(faces.images[2].shape), cmap=plt.cm.bone)
|
|
57
|
+
|
|
58
|
+
plt.imshow(pca.components_[18].reshape(faces.images[0].shape), cmap=plt.cm.bone)
|
|
59
|
+
|
|
60
|
+
plt.imshow(pca.components_[99].reshape(faces.images[0].shape), cmap=plt.cm.bone)
|
|
61
|
+
|
|
62
|
+
fig = plt.figure(figsize=(8, 6))
|
|
63
|
+
for i in range(18):
|
|
64
|
+
ax = fig.add_subplot(4, 5, i + 1, xticks=[], yticks=[])
|
|
65
|
+
ax.imshow(pca.components_[i].reshape(faces.images[0].shape), cmap=plt.cm.bone)
|
|
66
|
+
|
|
67
|
+
# Eigen space
|
|
68
|
+
faces_pca = pca.fit_transform(faces.data) # fit and transform the data to the new space
|
|
69
|
+
print(faces_pca.shape)
|
|
70
|
+
|
|
71
|
+
# 400 dataset, 100 features
|
|
72
|
+
# if 0.9 passed ==> (400,66) ==> using only 66 features you will cover 90% of the variance in the data. So, you can reduce the dimensionality of the data by using only 66 features instead of 100
|
|
73
|
+
|
|
74
|
+
faces_proj = pca.inverse_transform(faces_pca) # inverse transform the data back to the original space
|
|
75
|
+
print(faces_proj.shape)
|
|
76
|
+
|
|
77
|
+
plt.imshow(faces_proj[18].reshape(faces.images[0].shape), cmap=plt.cm.bone)
|
|
78
|
+
|
|
79
|
+
# Cross checking with the original image
|
|
80
|
+
# printing og image
|
|
81
|
+
|
|
82
|
+
plt.imshow(k, cmap=plt.cm.bone)
|
|
83
|
+
|
|
84
|
+
# do the same for your own image
|
|
85
|
+
|
|
86
|
+
# pehele 0.9 variance ke saath then show the reconstructed image
|
|
87
|
+
# then show har principal component mein kya store hua hai - uske observation ke according decide how many pc should be used
|
|
88
|
+
|
|
89
|
+
import os
|
|
90
|
+
import cv2
|
|
91
|
+
import numpy as np
|
|
92
|
+
import matplotlib.pyplot as plt
|
|
93
|
+
from sklearn.decomposition import PCA
|
|
94
|
+
from sklearn.metrics import mean_squared_error
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
folder_path = "pics"
|
|
98
|
+
target_size = (64, 64)
|
|
99
|
+
images = []
|
|
100
|
+
|
|
101
|
+
for filename in os.listdir(folder_path):
|
|
102
|
+
img_path = os.path.join(folder_path, filename)
|
|
103
|
+
# Read in grayscale
|
|
104
|
+
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
|
|
105
|
+
if img is not None:
|
|
106
|
+
img_resized = cv2.resize(img, target_size)
|
|
107
|
+
images.append(img_resized)
|
|
108
|
+
|
|
109
|
+
images = np.array(images, dtype=np.float32) / 255.0
|
|
110
|
+
|
|
111
|
+
n_samples, h, w = images.shape
|
|
112
|
+
X = images.reshape((n_samples, h * w))
|
|
113
|
+
|
|
114
|
+
print(f"Loaded {n_samples} images. Flattened shape: {X.shape}")
|
|
115
|
+
|
|
116
|
+
print("Flattened data shape:", X.shape)
|
|
117
|
+
|
|
118
|
+
images
|
|
119
|
+
|
|
120
|
+
k = images[10]
|
|
121
|
+
print("Single image shape:", k.shape)
|
|
122
|
+
|
|
123
|
+
import matplotlib.pyplot as plt
|
|
124
|
+
plt.imshow(k, cmap=plt.cm.bone)
|
|
125
|
+
|
|
126
|
+
fig = plt.figure(figsize=(10, 8))
|
|
127
|
+
|
|
128
|
+
for i in range(10):
|
|
129
|
+
|
|
130
|
+
ax = fig.add_subplot(3, 5, i + 1)
|
|
131
|
+
|
|
132
|
+
ax.imshow(images[i], cmap="gray")
|
|
133
|
+
|
|
134
|
+
ax.axis("off")
|
|
135
|
+
|
|
136
|
+
plt.show()
|
|
137
|
+
|
|
138
|
+
n_images = images.shape[0]
|
|
139
|
+
img_flat = images.reshape(n_images, 64 * 64)
|
|
140
|
+
img_flat = img_flat.astype("float32") / 255.0
|
|
141
|
+
print(img_flat.shape)
|
|
142
|
+
|
|
143
|
+
from sklearn.decomposition import PCA
|
|
144
|
+
pca = PCA(0.90)
|
|
145
|
+
pca.fit(img_flat)
|
|
146
|
+
|
|
147
|
+
print("Original number of features:", img_flat.shape[1])
|
|
148
|
+
print("Number of principal components:",
|
|
149
|
+
pca.n_components_)
|
|
150
|
+
|
|
151
|
+
print("Explained Variance Ratio:")
|
|
152
|
+
print(pca.explained_variance_ratio_)
|
|
153
|
+
|
|
154
|
+
import numpy as np
|
|
155
|
+
import matplotlib.pyplot as plt
|
|
156
|
+
|
|
157
|
+
cumulative_variance = np.cumsum(
|
|
158
|
+
pca.explained_variance_ratio_
|
|
159
|
+
)
|
|
160
|
+
plt.plot(cumulative_variance)
|
|
161
|
+
plt.xlabel("Number of Principal Components")
|
|
162
|
+
plt.ylabel("Cumulative Explained Variance")
|
|
163
|
+
plt.axhline(y=0.90, color='r', linestyle='--', label='90% Variance Threshold')
|
|
164
|
+
plt.legend()
|
|
165
|
+
plt.title("PCA Explained Variance")
|
|
166
|
+
plt.grid()
|
|
167
|
+
plt.show()
|
|
168
|
+
|
|
169
|
+
images_pca = pca.transform(img_flat)
|
|
170
|
+
print("Original shape:",img_flat.shape)
|
|
171
|
+
print("PCA transformed shape:",images_pca.shape)
|
|
172
|
+
|
|
173
|
+
images_reconstructed = pca.inverse_transform(images_pca)
|
|
174
|
+
print(images_reconstructed.shape)
|
|
175
|
+
|
|
176
|
+
plt.imshow(
|
|
177
|
+
images_reconstructed[0].reshape(64, 64),
|
|
178
|
+
cmap="gray"
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
plt.title("Reconstructed Image")
|
|
182
|
+
plt.axis("off")
|
|
183
|
+
plt.show()
|
|
184
|
+
|
|
185
|
+
plt.imshow(
|
|
186
|
+
images_reconstructed[1].reshape(64, 64),
|
|
187
|
+
cmap="gray"
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
plt.title("Reconstructed Image")
|
|
191
|
+
plt.axis("off")
|
|
192
|
+
|
|
193
|
+
plt.show()
|
|
194
|
+
|
|
195
|
+
plt.figure(figsize=(10, 4))
|
|
196
|
+
|
|
197
|
+
plt.subplot(1, 2, 1)
|
|
198
|
+
|
|
199
|
+
plt.imshow(
|
|
200
|
+
img_flat[0].reshape(64, 64),
|
|
201
|
+
cmap="gray"
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
plt.title("Original Image")
|
|
205
|
+
plt.axis("off")
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
plt.subplot(1, 2, 2)
|
|
209
|
+
|
|
210
|
+
plt.imshow(
|
|
211
|
+
images_reconstructed[0].reshape(64, 64),
|
|
212
|
+
cmap="gray"
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
plt.title("PCA Reconstructed Image")
|
|
216
|
+
plt.axis("off")
|
|
217
|
+
|
|
218
|
+
plt.show()
|
|
219
|
+
|
|
220
|
+
fig = plt.figure(figsize=(10, 8))
|
|
221
|
+
|
|
222
|
+
n_components_to_show = min(10, pca.components_.shape[0])
|
|
223
|
+
|
|
224
|
+
for i in range(n_components_to_show):
|
|
225
|
+
|
|
226
|
+
ax = fig.add_subplot(2, 5, i + 1)
|
|
227
|
+
|
|
228
|
+
ax.imshow(
|
|
229
|
+
pca.components_[i].reshape(64, 64),
|
|
230
|
+
cmap="gray"
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
ax.set_title("PC " + str(i + 1))
|
|
234
|
+
|
|
235
|
+
ax.axis("off")
|
|
236
|
+
|
|
237
|
+
plt.show()
|
|
238
|
+
|
|
239
|
+
pca = PCA(3)
|
|
240
|
+
pca.fit(img_flat)
|
|
241
|
+
|
|
242
|
+
images_pca1 = pca.transform(img_flat)
|
|
243
|
+
|
|
244
|
+
print("Original shape:",img_flat.shape)
|
|
245
|
+
print("PCA transformed shape:",images_pca1.shape)
|
|
246
|
+
|
|
247
|
+
images_reconstructed = pca.inverse_transform(images_pca1)
|
|
248
|
+
print(images_reconstructed.shape)
|
|
249
|
+
|
|
250
|
+
print("Original number of features:", img_flat.shape[1])
|
|
251
|
+
print("Number of principal components:",pca.n_components_)
|
|
252
|
+
|
|
253
|
+
plt.imshow(
|
|
254
|
+
images_reconstructed[0].reshape(64, 64),
|
|
255
|
+
cmap="gray"
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
plt.title("Reconstructed Image using 3 Principal Components")
|
|
259
|
+
plt.axis("off")
|
|
260
|
+
plt.show()
|
|
261
|
+
|
|
262
|
+
print("Explained Variance Ratio:")
|
|
263
|
+
|
|
264
|
+
print(pca.explained_variance_ratio_)
|
|
265
|
+
|
|
266
|
+
# PCA with 3 components
|
|
267
|
+
pca3 = PCA(n_components=3)
|
|
268
|
+
img_pca3 = pca3.fit_transform(img_flat)
|
|
269
|
+
recon3 = pca3.inverse_transform(img_pca3)
|
|
270
|
+
|
|
271
|
+
# PCA with 8 components
|
|
272
|
+
pca8 = PCA(n_components=8)
|
|
273
|
+
img_pca8 = pca8.fit_transform(img_flat)
|
|
274
|
+
recon8 = pca8.inverse_transform(img_pca8)
|
|
275
|
+
|
|
276
|
+
# Reconstruction error
|
|
277
|
+
mse3 = np.mean((img_flat - recon3) ** 2)
|
|
278
|
+
mse8 = np.mean((img_flat - recon8) ** 2)
|
|
279
|
+
|
|
280
|
+
print("MSE with 3 PCs:", mse3)
|
|
281
|
+
print("MSE with 8 PCs:", mse8)
|
|
282
|
+
|
|
283
|
+
print("Variance explained by 3 PCs:",
|
|
284
|
+
np.sum(pca3.explained_variance_ratio_))
|
|
285
|
+
|
|
286
|
+
print("Variance explained by 8 PCs:",
|
|
287
|
+
np.sum(pca8.explained_variance_ratio_))
|
|
288
|
+
|
|
289
|
+
pca1 = PCA(n_components=1)
|
|
290
|
+
img_pca1 = pca1.fit_transform(img_flat)
|
|
291
|
+
recon1 = pca1.inverse_transform(img_pca1)
|
|
292
|
+
|
|
293
|
+
# PCA with 8 components
|
|
294
|
+
pca8 = PCA(n_components=8)
|
|
295
|
+
img_pca8 = pca8.fit_transform(img_flat)
|
|
296
|
+
recon8 = pca8.inverse_transform(img_pca8)
|
|
297
|
+
|
|
298
|
+
# Reconstruction error
|
|
299
|
+
mse1 = np.mean((img_flat - recon1) ** 2)
|
|
300
|
+
mse8 = np.mean((img_flat - recon8) ** 2)
|
|
301
|
+
|
|
302
|
+
print("MSE with 3 PCs:", mse3)
|
|
303
|
+
print("MSE with 8 PCs:", mse8)
|
|
304
|
+
|
|
305
|
+
print("Variance explained by 1 PCs:",
|
|
306
|
+
np.sum(pca1.explained_variance_ratio_))
|
|
307
|
+
|
|
308
|
+
print("Variance explained by 8 PCs:",
|
|
309
|
+
np.sum(pca8.explained_variance_ratio_))
|
|
310
|
+
|
|
311
|
+
images_reconstructed = pca.inverse_transform(images_pca1)
|
|
312
|
+
print(images_reconstructed.shape)
|
|
313
|
+
|
|
314
|
+
plt.figure(figsize=(5, 5))
|
|
315
|
+
|
|
316
|
+
plt.imshow(
|
|
317
|
+
recon1[0].reshape(64, 64),
|
|
318
|
+
cmap="gray"
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
plt.title("Reconstructed Image using 1 Principal Component")
|
|
322
|
+
plt.axis("off")
|
|
323
|
+
plt.show()
|
|
324
|
+
|
|
325
|
+
n_components_to_show = min(10, pca1.n_components_)
|
|
326
|
+
|
|
327
|
+
for i in range(n_components_to_show):
|
|
328
|
+
plt.subplot(2, 5, i + 1)
|
|
329
|
+
plt.imshow(
|
|
330
|
+
pca1.components_[i].reshape(64, 64),
|
|
331
|
+
cmap="gray"
|
|
332
|
+
)
|
|
333
|
+
plt.title("PC " + str(i + 1))
|
|
334
|
+
plt.axis("off")
|
|
335
|
+
plt.show()
|
fomltools/labs/lab10.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Lab 10 code imported from the uploaded FOML notebook."""
|
|
2
|
+
|
|
3
|
+
def run():
|
|
4
|
+
"""Run the original lab code in notebook-cell order."""
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
df = pd.DataFrame({
|
|
8
|
+
"X1": [4, 2, 2, 3, 4, 9, 6, 9, 8, 10],
|
|
9
|
+
"X2": [1, 4, 3, 6, 4, 10, 8, 5, 7, 8],
|
|
10
|
+
"Group": [1, 1, 1, 1, 1, 2, 2, 2, 2, 2]
|
|
11
|
+
})
|
|
12
|
+
df
|
|
13
|
+
|
|
14
|
+
import matplotlib.pyplot as plt
|
|
15
|
+
import numpy as np
|
|
16
|
+
plt.figure(figsize=(6,5))
|
|
17
|
+
plt.scatter(df["X1"],df["X2"],c=df["Group"],s=70)
|
|
18
|
+
plt.grid(True)
|
|
19
|
+
plt.show()
|
|
20
|
+
|
|
21
|
+
#mean
|
|
22
|
+
df1=df[df["Group"]==1].copy()
|
|
23
|
+
df2=df[df["Group"]==2].copy()
|
|
24
|
+
print("Group1 ")
|
|
25
|
+
print(df1)
|
|
26
|
+
print("Group2")
|
|
27
|
+
print(df2)
|
|
28
|
+
|
|
29
|
+
mu1=df1[["X1","X2"]].mean().values
|
|
30
|
+
mu2=df2[["X1","X2"]].mean().values
|
|
31
|
+
print(mu1,mu2)
|
|
32
|
+
|
|
33
|
+
#scatter
|
|
34
|
+
d=(mu1-mu2).reshape(1,2)
|
|
35
|
+
sb=d.T@d# @ is used for matrix multiplication
|
|
36
|
+
print(d)#diff between the means
|
|
37
|
+
print(sb)#between class matrix
|
|
38
|
+
|
|
39
|
+
#within the matrix
|
|
40
|
+
df1["x1_c"]=df1["X1"]-mu1[0]
|
|
41
|
+
df1["x2_c"]=df1["X2"]-mu1[1]
|
|
42
|
+
df2["x1_c"]=df2["X1"]-mu2[0]
|
|
43
|
+
df2["x2_c"]=df2["X1"]-mu2[1]
|
|
44
|
+
|
|
45
|
+
print(df1)
|
|
46
|
+
print(df2)
|
|
47
|
+
|
|
48
|
+
x1c=df1[["x1_c","x2_c"]].values
|
|
49
|
+
x2c=df2[["x1_c","x2_c"]].values
|
|
50
|
+
|
|
51
|
+
s1=x1c.T @ x1c
|
|
52
|
+
s2=x2c.T @ x2c
|
|
53
|
+
sw=s1+s2
|
|
54
|
+
print(s1,s2,sw)
|
|
55
|
+
|
|
56
|
+
a=np.linalg.pinv(sw)@sb
|
|
57
|
+
print(a)
|
|
58
|
+
|
|
59
|
+
eigvalues,eigvectors=np.linalg.eig(a)
|
|
60
|
+
idx=np.argsort(eigvalues)[::-1]
|
|
61
|
+
eigvalues=eigvalues[idx]
|
|
62
|
+
eigvectors=eigvectors[:,idx]
|
|
63
|
+
w=np.real(eigvectors[:,0])
|
|
64
|
+
w=w/np.linalg.norm(w)
|
|
65
|
+
print(eigvalues,w)
|
|
66
|
+
|
|
67
|
+
X=df[["X1","X2"]].values
|
|
68
|
+
y= df["Group"].values
|
|
69
|
+
z= X@ w
|
|
70
|
+
proj_table =pd.DataFrame({
|
|
71
|
+
"X1":df["X1"],
|
|
72
|
+
"X2":df["X2"],
|
|
73
|
+
"Actual Group ":y,
|
|
74
|
+
"LDA Score":z
|
|
75
|
+
|
|
76
|
+
})
|
|
77
|
+
proj_table
|
|
78
|
+
|
|
79
|
+
proj=z.reshape(-1,1)*w.reshape(1,-1)
|
|
80
|
+
plt.figure(figsize=(6,5))
|
|
81
|
+
plt.scatter(proj[:,0],proj[:,1],c=y,s=70)
|
|
82
|
+
plt.show()
|
|
83
|
+
|
|
84
|
+
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
|
|
85
|
+
from sklearn.metrics import confusion_matrix, accuracy_score
|
|
86
|
+
|
|
87
|
+
X = df[["X1", "X2"]].values
|
|
88
|
+
y = df["Group"].values
|
|
89
|
+
|
|
90
|
+
lda = LinearDiscriminantAnalysis(n_components=1)
|
|
91
|
+
|
|
92
|
+
X_lda = lda.fit_transform(X, y)
|
|
93
|
+
predict = lda.predict(X)
|
|
94
|
+
|
|
95
|
+
print(X_lda.shape)
|
|
96
|
+
print(predict)
|
|
97
|
+
|
|
98
|
+
cm=confusion_matrix(y,predict)
|
|
99
|
+
acc=accuracy_score(y,predict)
|
|
100
|
+
print(cm, acc)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
grand_mean = np.mean(X, axis=0)
|
|
104
|
+
|
|
105
|
+
classification_rate = accuracy_score(y, predict)
|
|
106
|
+
|
|
107
|
+
print("\nGrand Mean:")
|
|
108
|
+
print(grand_mean)
|
|
109
|
+
|
|
110
|
+
print("\nClassification Rate:", classification_rate)
|
|
111
|
+
print("Classification Rate (%):", classification_rate * 100)
|