|
a |
|
b/train_classifier.py |
|
|
1 |
|
|
|
2 |
|
|
|
3 |
# train_classifier.py |
|
|
4 |
|
|
|
5 |
import os |
|
|
6 |
import numpy as np |
|
|
7 |
import cv2 |
|
|
8 |
from tensorflow.keras.models import Sequential |
|
|
9 |
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout |
|
|
10 |
from sklearn.model_selection import train_test_split |
|
|
11 |
from tensorflow.keras.utils import to_categorical |
|
|
12 |
|
|
|
13 |
IMAGE_SIZE = 128 |
|
|
14 |
DATASET_PATH = "dataset" |
|
|
15 |
|
|
|
16 |
def load_data(): |
|
|
17 |
images = [] |
|
|
18 |
labels = [] |
|
|
19 |
class_names = os.listdir(DATASET_PATH) |
|
|
20 |
class_map = {name: i for i, name in enumerate(class_names)} |
|
|
21 |
|
|
|
22 |
for class_name in class_names: |
|
|
23 |
img_folder = os.path.join(DATASET_PATH, class_name, "images") |
|
|
24 |
for img_name in os.listdir(img_folder): |
|
|
25 |
img_path = os.path.join(img_folder, img_name) |
|
|
26 |
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) |
|
|
27 |
|
|
|
28 |
if img is not None: |
|
|
29 |
img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) / 255.0 |
|
|
30 |
images.append(img) |
|
|
31 |
labels.append(class_map[class_name]) |
|
|
32 |
|
|
|
33 |
X = np.array(images).reshape(-1, IMAGE_SIZE, IMAGE_SIZE, 1) |
|
|
34 |
y = to_categorical(np.array(labels)) |
|
|
35 |
return X, y, class_map |
|
|
36 |
|
|
|
37 |
def build_classifier(num_classes): |
|
|
38 |
model = Sequential() |
|
|
39 |
model.add(Conv2D(32, 3, activation='relu', input_shape=(IMAGE_SIZE, IMAGE_SIZE, 1))) |
|
|
40 |
model.add(MaxPooling2D(2)) |
|
|
41 |
model.add(Conv2D(64, 3, activation='relu')) |
|
|
42 |
model.add(MaxPooling2D(2)) |
|
|
43 |
model.add(Flatten()) |
|
|
44 |
model.add(Dense(128, activation='relu')) |
|
|
45 |
model.add(Dropout(0.3)) |
|
|
46 |
model.add(Dense(num_classes, activation='softmax')) |
|
|
47 |
|
|
|
48 |
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) |
|
|
49 |
return model |
|
|
50 |
|
|
|
51 |
# Load & train |
|
|
52 |
X, y, class_map = load_data() |
|
|
53 |
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2) |
|
|
54 |
|
|
|
55 |
model = build_classifier(num_classes=len(class_map)) |
|
|
56 |
model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=10, batch_size=16) |
|
|
57 |
|
|
|
58 |
model.save("app/model/classifier_model.h5") |
|
|
59 |
print("Classifier model saved to app/model/classifier_model.h5") |
|
|
60 |
print(f" Class Map: {class_map}") |