cvip-labs 0.1.0__tar.gz
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.
- cvip_labs-0.1.0/PKG-INFO +41 -0
- cvip_labs-0.1.0/README.md +26 -0
- cvip_labs-0.1.0/cvip_labs/__init__.py +5 -0
- cvip_labs-0.1.0/cvip_labs/run_exp4.py +143 -0
- cvip_labs-0.1.0/cvip_labs/run_exp5.py +124 -0
- cvip_labs-0.1.0/cvip_labs.egg-info/PKG-INFO +41 -0
- cvip_labs-0.1.0/cvip_labs.egg-info/SOURCES.txt +10 -0
- cvip_labs-0.1.0/cvip_labs.egg-info/dependency_links.txt +1 -0
- cvip_labs-0.1.0/cvip_labs.egg-info/requires.txt +6 -0
- cvip_labs-0.1.0/cvip_labs.egg-info/top_level.txt +1 -0
- cvip_labs-0.1.0/pyproject.toml +24 -0
- cvip_labs-0.1.0/setup.cfg +4 -0
cvip_labs-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cvip_labs
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: CVIP 6th sem lab helpers - MNIST and CNN experiments
|
|
5
|
+
Author: cvip_labs
|
|
6
|
+
Project-URL: Homepage, https://pypi.org/project/cvip_labs
|
|
7
|
+
Requires-Python: >=3.8
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: numpy
|
|
10
|
+
Requires-Dist: matplotlib
|
|
11
|
+
Requires-Dist: scikit-learn
|
|
12
|
+
Requires-Dist: torch
|
|
13
|
+
Requires-Dist: tensorflow
|
|
14
|
+
Requires-Dist: opencv-python
|
|
15
|
+
|
|
16
|
+
# cvip_labs
|
|
17
|
+
|
|
18
|
+
CVIP 6th sem lab helpers.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
pip install cvip_labs
|
|
22
|
+
|
|
23
|
+
## Exp 4 - MNIST SVM + Neural Network
|
|
24
|
+
from cvip_labs import run_exp4
|
|
25
|
+
X_train, X_test, y_train, y_test = run_exp4.load_data()
|
|
26
|
+
svm_model = run_exp4.train_svm(X_train, y_train)
|
|
27
|
+
svm_acc = run_exp4.evaluate(svm_model, X_test, y_test)
|
|
28
|
+
nn_model = run_exp4.train_nn(X_train, y_train, epochs=5)
|
|
29
|
+
nn_acc = run_exp4.evaluate_nn(nn_model, X_test, y_test)
|
|
30
|
+
run_exp4.plot_results()
|
|
31
|
+
|
|
32
|
+
## Exp 5 - CNN Image Classifier
|
|
33
|
+
from cvip_labs import run_exp5
|
|
34
|
+
train, val, test, class_names = run_exp5.load_data(data_dir='exp5')
|
|
35
|
+
model = run_exp5.build_model()
|
|
36
|
+
model.summary()
|
|
37
|
+
hist = run_exp5.train_model(model, train, val, epochs=20)
|
|
38
|
+
run_exp5.plot_results(hist)
|
|
39
|
+
run_exp5.evaluate(model, test)
|
|
40
|
+
run_exp5.predict(model, class_names, img_path='images6.jpg')
|
|
41
|
+
run_exp5.save_model(model)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# cvip_labs
|
|
2
|
+
|
|
3
|
+
CVIP 6th sem lab helpers.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
pip install cvip_labs
|
|
7
|
+
|
|
8
|
+
## Exp 4 - MNIST SVM + Neural Network
|
|
9
|
+
from cvip_labs import run_exp4
|
|
10
|
+
X_train, X_test, y_train, y_test = run_exp4.load_data()
|
|
11
|
+
svm_model = run_exp4.train_svm(X_train, y_train)
|
|
12
|
+
svm_acc = run_exp4.evaluate(svm_model, X_test, y_test)
|
|
13
|
+
nn_model = run_exp4.train_nn(X_train, y_train, epochs=5)
|
|
14
|
+
nn_acc = run_exp4.evaluate_nn(nn_model, X_test, y_test)
|
|
15
|
+
run_exp4.plot_results()
|
|
16
|
+
|
|
17
|
+
## Exp 5 - CNN Image Classifier
|
|
18
|
+
from cvip_labs import run_exp5
|
|
19
|
+
train, val, test, class_names = run_exp5.load_data(data_dir='exp5')
|
|
20
|
+
model = run_exp5.build_model()
|
|
21
|
+
model.summary()
|
|
22
|
+
hist = run_exp5.train_model(model, train, val, epochs=20)
|
|
23
|
+
run_exp5.plot_results(hist)
|
|
24
|
+
run_exp5.evaluate(model, test)
|
|
25
|
+
run_exp5.predict(model, class_names, img_path='images6.jpg')
|
|
26
|
+
run_exp5.save_model(model)
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import matplotlib.pyplot as plt
|
|
3
|
+
|
|
4
|
+
_data = {}
|
|
5
|
+
_loss_history = []
|
|
6
|
+
|
|
7
|
+
def load_data():
|
|
8
|
+
"""Load and preprocess MNIST dataset"""
|
|
9
|
+
from tensorflow.keras.datasets import mnist
|
|
10
|
+
|
|
11
|
+
print("Loading MNIST dataset...")
|
|
12
|
+
(x_train, y_train), (x_test, y_test) = mnist.load_data()
|
|
13
|
+
|
|
14
|
+
# Show sample images
|
|
15
|
+
plt.figure(figsize=(10, 2))
|
|
16
|
+
for i in range(5):
|
|
17
|
+
plt.subplot(1, 5, i+1)
|
|
18
|
+
plt.imshow(x_train[i], cmap='gray')
|
|
19
|
+
plt.title(str(y_train[i]))
|
|
20
|
+
plt.axis('off')
|
|
21
|
+
plt.suptitle("Sample MNIST Images")
|
|
22
|
+
plt.tight_layout()
|
|
23
|
+
plt.show()
|
|
24
|
+
|
|
25
|
+
X_train = x_train.reshape(-1, 784) / 255.0
|
|
26
|
+
X_test = x_test.reshape(-1, 784) / 255.0
|
|
27
|
+
|
|
28
|
+
_data['X_train'] = X_train
|
|
29
|
+
_data['X_test'] = X_test
|
|
30
|
+
_data['y_train'] = y_train
|
|
31
|
+
_data['y_test'] = y_test
|
|
32
|
+
|
|
33
|
+
print(f"Train samples: {X_train.shape[0]}, Test samples: {X_test.shape[0]}")
|
|
34
|
+
return X_train, X_test, y_train, y_test
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def train_svm(X_train, y_train):
|
|
38
|
+
"""Train SVM classifier on MNIST"""
|
|
39
|
+
from sklearn.svm import SVC
|
|
40
|
+
|
|
41
|
+
print("Training SVM on 10,000 samples...")
|
|
42
|
+
svm_model = SVC()
|
|
43
|
+
svm_model.fit(X_train[:10000], y_train[:10000])
|
|
44
|
+
print("SVM training complete!")
|
|
45
|
+
_data['svm'] = svm_model
|
|
46
|
+
return svm_model
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def evaluate(svm_model, X_test, y_test):
|
|
50
|
+
"""Evaluate SVM model on test data"""
|
|
51
|
+
from sklearn.metrics import accuracy_score
|
|
52
|
+
|
|
53
|
+
y_pred = svm_model.predict(X_test)
|
|
54
|
+
acc = accuracy_score(y_test, y_pred)
|
|
55
|
+
print(f"SVM Accuracy: {acc:.4f}")
|
|
56
|
+
_data['svm_acc'] = acc
|
|
57
|
+
return acc
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def train_nn(X_train, y_train, epochs=5):
|
|
61
|
+
"""Train PyTorch Neural Network on MNIST"""
|
|
62
|
+
import torch
|
|
63
|
+
import torch.nn as nn
|
|
64
|
+
|
|
65
|
+
global _loss_history
|
|
66
|
+
_loss_history = []
|
|
67
|
+
_acc_history = []
|
|
68
|
+
|
|
69
|
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
70
|
+
print(f"Training Neural Network on {device} for {epochs} epochs...")
|
|
71
|
+
|
|
72
|
+
nn_model = nn.Sequential(
|
|
73
|
+
nn.Linear(784, 64),
|
|
74
|
+
nn.ReLU(),
|
|
75
|
+
nn.Linear(64, 10)
|
|
76
|
+
).to(device)
|
|
77
|
+
|
|
78
|
+
Xt = torch.tensor(X_train, dtype=torch.float32).to(device)
|
|
79
|
+
yt = torch.tensor(y_train, dtype=torch.long).to(device)
|
|
80
|
+
opt = torch.optim.Adam(nn_model.parameters())
|
|
81
|
+
|
|
82
|
+
for epoch in range(epochs):
|
|
83
|
+
out = nn_model(Xt)
|
|
84
|
+
loss = nn.CrossEntropyLoss()(out, yt)
|
|
85
|
+
opt.zero_grad(); loss.backward(); opt.step()
|
|
86
|
+
|
|
87
|
+
preds = torch.argmax(out, dim=1).cpu().numpy()
|
|
88
|
+
acc = np.mean(preds == y_train)
|
|
89
|
+
|
|
90
|
+
_loss_history.append(loss.item())
|
|
91
|
+
_acc_history.append(acc)
|
|
92
|
+
print(f" Epoch {epoch+1}/{epochs} — Loss: {loss.item():.4f} | Accuracy: {acc:.4f}")
|
|
93
|
+
|
|
94
|
+
_data['nn_model'] = nn_model
|
|
95
|
+
_data['device'] = device
|
|
96
|
+
_data['acc_history'] = _acc_history
|
|
97
|
+
return nn_model
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def evaluate_nn(nn_model, X_test, y_test):
|
|
101
|
+
"""Evaluate Neural Network on test data"""
|
|
102
|
+
import torch
|
|
103
|
+
|
|
104
|
+
device = _data.get('device', torch.device('cpu'))
|
|
105
|
+
Xtest_t = torch.tensor(X_test, dtype=torch.float32).to(device)
|
|
106
|
+
|
|
107
|
+
with torch.no_grad():
|
|
108
|
+
preds = torch.argmax(nn_model(Xtest_t), dim=1).cpu().numpy()
|
|
109
|
+
|
|
110
|
+
acc = np.mean(preds == y_test)
|
|
111
|
+
print(f"Neural Network Accuracy: {acc:.4f}")
|
|
112
|
+
_data['nn_acc'] = acc
|
|
113
|
+
return acc
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def plot_results():
|
|
117
|
+
"""Plot epoch vs loss and epoch vs accuracy graphs"""
|
|
118
|
+
epochs = range(1, len(_loss_history) + 1)
|
|
119
|
+
acc_history = _data.get('acc_history', [])
|
|
120
|
+
|
|
121
|
+
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
|
|
122
|
+
|
|
123
|
+
# Graph 1 - Epoch vs Loss
|
|
124
|
+
ax[0].plot(epochs, _loss_history, marker='o', color='steelblue', linewidth=2)
|
|
125
|
+
ax[0].set_title("Epoch vs Loss")
|
|
126
|
+
ax[0].set_xlabel("Epoch")
|
|
127
|
+
ax[0].set_ylabel("Loss")
|
|
128
|
+
ax[0].grid(True)
|
|
129
|
+
|
|
130
|
+
# Graph 2 - Epoch vs Accuracy
|
|
131
|
+
ax[1].plot(epochs, acc_history, marker='s', color='coral', linewidth=2)
|
|
132
|
+
ax[1].set_title("Epoch vs Accuracy")
|
|
133
|
+
ax[1].set_xlabel("Epoch")
|
|
134
|
+
ax[1].set_ylabel("Accuracy")
|
|
135
|
+
ax[1].set_ylim(0, 1)
|
|
136
|
+
ax[1].grid(True)
|
|
137
|
+
|
|
138
|
+
plt.tight_layout()
|
|
139
|
+
plt.show()
|
|
140
|
+
|
|
141
|
+
print("\n--- Final Summary ---")
|
|
142
|
+
print(f"SVM Accuracy : {_data.get('svm_acc', 'N/A')}")
|
|
143
|
+
print(f"Neural Net Accuracy : {_data.get('nn_acc', 'N/A')}")
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import matplotlib.pyplot as plt
|
|
2
|
+
|
|
3
|
+
_state = {}
|
|
4
|
+
|
|
5
|
+
def load_data(data_dir):
|
|
6
|
+
"""Load and split image dataset from directory"""
|
|
7
|
+
import tensorflow as tf
|
|
8
|
+
|
|
9
|
+
for gpu in tf.config.list_physical_devices('GPU'):
|
|
10
|
+
tf.config.experimental.set_memory_growth(gpu, True)
|
|
11
|
+
|
|
12
|
+
print(f"Loading dataset from: {data_dir}")
|
|
13
|
+
data = tf.keras.utils.image_dataset_from_directory(
|
|
14
|
+
data_dir, image_size=(256, 256), batch_size=32
|
|
15
|
+
)
|
|
16
|
+
class_names = data.class_names
|
|
17
|
+
print(f"Classes found: {class_names}")
|
|
18
|
+
|
|
19
|
+
data = data.shuffle(1000).map(lambda x, y: (x / 255.0, y))
|
|
20
|
+
n = len(data)
|
|
21
|
+
train = data.take(int(0.7 * n))
|
|
22
|
+
val = data.skip(int(0.7 * n)).take(int(0.2 * n))
|
|
23
|
+
test = data.skip(int(0.9 * n))
|
|
24
|
+
|
|
25
|
+
print(f"Train batches: {int(0.7*n)} | Val batches: {int(0.2*n)} | Test batches: {n - int(0.9*n)}")
|
|
26
|
+
|
|
27
|
+
_state['class_names'] = class_names
|
|
28
|
+
return train, val, test, class_names
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build_model():
|
|
32
|
+
"""Build CNN model architecture"""
|
|
33
|
+
from tensorflow.keras import models, layers, metrics
|
|
34
|
+
|
|
35
|
+
print("Building CNN model...")
|
|
36
|
+
model = models.Sequential([
|
|
37
|
+
layers.Conv2D(16, (3,3), activation='relu', input_shape=(256,256,3)),
|
|
38
|
+
layers.MaxPooling2D(),
|
|
39
|
+
layers.Conv2D(32, (3,3), activation='relu'),
|
|
40
|
+
layers.MaxPooling2D(),
|
|
41
|
+
layers.Conv2D(64, (3,3), activation='relu'),
|
|
42
|
+
layers.MaxPooling2D(),
|
|
43
|
+
layers.Flatten(),
|
|
44
|
+
layers.Dense(128, activation='relu'),
|
|
45
|
+
layers.Dropout(0.5),
|
|
46
|
+
layers.Dense(1, activation='sigmoid')
|
|
47
|
+
])
|
|
48
|
+
model.compile(
|
|
49
|
+
optimizer='adam',
|
|
50
|
+
loss='binary_crossentropy',
|
|
51
|
+
metrics=['accuracy',
|
|
52
|
+
metrics.Precision(name='precision'),
|
|
53
|
+
metrics.Recall(name='recall')]
|
|
54
|
+
)
|
|
55
|
+
_state['model'] = model
|
|
56
|
+
return model
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def train_model(model, train, val, epochs=20):
|
|
60
|
+
"""Train CNN model with early stopping"""
|
|
61
|
+
from tensorflow.keras import callbacks
|
|
62
|
+
|
|
63
|
+
early_stop = callbacks.EarlyStopping(
|
|
64
|
+
monitor='val_loss', patience=3, restore_best_weights=True
|
|
65
|
+
)
|
|
66
|
+
print(f"Training model for {epochs} epochs...")
|
|
67
|
+
hist = model.fit(
|
|
68
|
+
train, epochs=epochs,
|
|
69
|
+
validation_data=val,
|
|
70
|
+
callbacks=[early_stop]
|
|
71
|
+
)
|
|
72
|
+
_state['hist'] = hist
|
|
73
|
+
return hist
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def plot_results(hist):
|
|
77
|
+
"""Plot training loss and accuracy curves"""
|
|
78
|
+
fig, ax = plt.subplots(1, 2, figsize=(12, 5))
|
|
79
|
+
|
|
80
|
+
ax[0].plot(hist.history['loss'], label='Loss')
|
|
81
|
+
ax[0].plot(hist.history['val_loss'], label='Val Loss')
|
|
82
|
+
ax[0].set_title('Loss'); ax[0].legend()
|
|
83
|
+
|
|
84
|
+
ax[1].plot(hist.history['accuracy'], label='Accuracy')
|
|
85
|
+
ax[1].plot(hist.history['val_accuracy'], label='Val Accuracy')
|
|
86
|
+
ax[1].set_title('Accuracy'); ax[1].legend()
|
|
87
|
+
|
|
88
|
+
plt.tight_layout()
|
|
89
|
+
plt.show()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def evaluate(model, test):
|
|
93
|
+
"""Evaluate model on test dataset"""
|
|
94
|
+
print("\nEvaluating on test data:")
|
|
95
|
+
results = model.evaluate(test)
|
|
96
|
+
return results
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def predict(model, class_names, img_path):
|
|
100
|
+
"""Predict class of a single image"""
|
|
101
|
+
import cv2
|
|
102
|
+
import numpy as np
|
|
103
|
+
|
|
104
|
+
img = cv2.imread(img_path)
|
|
105
|
+
img_resized = cv2.resize(img, (256, 256))
|
|
106
|
+
|
|
107
|
+
plt.imshow(cv2.cvtColor(img_resized, cv2.COLOR_BGR2RGB))
|
|
108
|
+
plt.title("Test Image"); plt.axis('off'); plt.show()
|
|
109
|
+
|
|
110
|
+
pred = model.predict(
|
|
111
|
+
numpy_expand := img_resized / 255.0,
|
|
112
|
+
)
|
|
113
|
+
pred = model.predict(__import__('numpy').expand_dims(img_resized / 255.0, axis=0))
|
|
114
|
+
label = class_names[int(pred[0][0] > 0.5)]
|
|
115
|
+
print(f"Predicted Class: {label}")
|
|
116
|
+
return label
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def save_model(model, path='models/imageclassifier.h5'):
|
|
120
|
+
"""Save trained model to disk"""
|
|
121
|
+
import os
|
|
122
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
123
|
+
model.save(path)
|
|
124
|
+
print(f"Model saved to {path}")
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cvip_labs
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: CVIP 6th sem lab helpers - MNIST and CNN experiments
|
|
5
|
+
Author: cvip_labs
|
|
6
|
+
Project-URL: Homepage, https://pypi.org/project/cvip_labs
|
|
7
|
+
Requires-Python: >=3.8
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: numpy
|
|
10
|
+
Requires-Dist: matplotlib
|
|
11
|
+
Requires-Dist: scikit-learn
|
|
12
|
+
Requires-Dist: torch
|
|
13
|
+
Requires-Dist: tensorflow
|
|
14
|
+
Requires-Dist: opencv-python
|
|
15
|
+
|
|
16
|
+
# cvip_labs
|
|
17
|
+
|
|
18
|
+
CVIP 6th sem lab helpers.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
pip install cvip_labs
|
|
22
|
+
|
|
23
|
+
## Exp 4 - MNIST SVM + Neural Network
|
|
24
|
+
from cvip_labs import run_exp4
|
|
25
|
+
X_train, X_test, y_train, y_test = run_exp4.load_data()
|
|
26
|
+
svm_model = run_exp4.train_svm(X_train, y_train)
|
|
27
|
+
svm_acc = run_exp4.evaluate(svm_model, X_test, y_test)
|
|
28
|
+
nn_model = run_exp4.train_nn(X_train, y_train, epochs=5)
|
|
29
|
+
nn_acc = run_exp4.evaluate_nn(nn_model, X_test, y_test)
|
|
30
|
+
run_exp4.plot_results()
|
|
31
|
+
|
|
32
|
+
## Exp 5 - CNN Image Classifier
|
|
33
|
+
from cvip_labs import run_exp5
|
|
34
|
+
train, val, test, class_names = run_exp5.load_data(data_dir='exp5')
|
|
35
|
+
model = run_exp5.build_model()
|
|
36
|
+
model.summary()
|
|
37
|
+
hist = run_exp5.train_model(model, train, val, epochs=20)
|
|
38
|
+
run_exp5.plot_results(hist)
|
|
39
|
+
run_exp5.evaluate(model, test)
|
|
40
|
+
run_exp5.predict(model, class_names, img_path='images6.jpg')
|
|
41
|
+
run_exp5.save_model(model)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
cvip_labs/__init__.py
|
|
4
|
+
cvip_labs/run_exp4.py
|
|
5
|
+
cvip_labs/run_exp5.py
|
|
6
|
+
cvip_labs.egg-info/PKG-INFO
|
|
7
|
+
cvip_labs.egg-info/SOURCES.txt
|
|
8
|
+
cvip_labs.egg-info/dependency_links.txt
|
|
9
|
+
cvip_labs.egg-info/requires.txt
|
|
10
|
+
cvip_labs.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cvip_labs
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cvip_labs"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "cvip_labs" }
|
|
10
|
+
]
|
|
11
|
+
description = "CVIP 6th sem lab helpers - MNIST and CNN experiments"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.8"
|
|
14
|
+
dependencies = [
|
|
15
|
+
"numpy",
|
|
16
|
+
"matplotlib",
|
|
17
|
+
"scikit-learn",
|
|
18
|
+
"torch",
|
|
19
|
+
"tensorflow",
|
|
20
|
+
"opencv-python",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://pypi.org/project/cvip_labs"
|