SpectraFaceAuth/AttendanceApp
0
1import numpy as np
2import pandas as pd
3import csv
4import tensorflow as tf
5from sklearn.model_selection import train_test_split
6import cv2
7from pathlib import Path
8from tensorflow.keras.models import Sequential
9from tensorflow.keras.layers import Dense, Flatten, Input
10from tensorflow.keras.optimizers import Adam
11from keras.applications import vgg16
12
13def ModelFineTuning():
14 # Define the path to your dataset
15 data_dir = Path('Dataset')
16 image_size = (224, 224) # VGGFace model expects 224x224 images
17
18 # Initialize dictionaries
19 candidates_dict = {}
20 labels_dict = {}
21
22 # Get all class folder names
23 class_folders = [folder.name for folder in data_dir.iterdir() if folder.is_dir()]
24 total_classes = len(class_folders)
25
26 # Assign labels to each class
27 for idx, class_name in enumerate(class_folders):
28 candidates_dict[class_name] = list(data_dir.glob(f'{class_name}/*'))
29 labels_dict[class_name] = idx
30
31 df = pd.DataFrame(list(labels_dict.items()), columns=['Candidate Name', 'Label'])
32 df.to_csv("candidate_labels.csv", index=False)
33
34 # Print the results
35 print('Images Dictionary:')
36 print(candidates_dict)
37 print('\nLabels Dictionary:')
38 print(labels_dict)
39
40 X, y = [], []
41 if len(candidates_dict.items()) == 0:
42 return False
43 for candidate_name, faces in candidates_dict.items():
44 for image in faces:
45 img = cv2.imread(str(image))
46 resized_img = cv2.resize(img, image_size)
47 X.append(resized_img)
48 y.append(labels_dict[candidate_name])
49
50 print(len(X))
51
52 X = np.array(X)
53 y = np.array(y)
54
55 X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
56
57 X_train_scaled = X_train / 255.0
58 X_test_scaled = X_test / 255.0
59
60 # Convert labels to one-hot encoding
61 y_train = tf.keras.utils.to_categorical(y_train, num_classes=total_classes)
62 y_test = tf.keras.utils.to_categorical(y_test, num_classes=total_classes)
63
64 # Load the pre-trained VGGFace model
65 base_model = vgg16.VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
66
67 # Ensure the base model layers are not trainable
68 for layer in base_model.layers:
69 layer.trainable = False
70
71 # Create a Sequential model and add layers
72 model = Sequential()
73 model.add(Input(shape=(224, 224, 3)))
74 model.add(base_model)
75 model.add(Flatten())
76 model.add(Dense(1024, activation='relu'))
77 model.add(Dense(512, activation='relu'))
78 model.add(Dense(total_classes, activation='softmax'))
79
80 # Compile the model
81 model.compile(optimizer=Adam(learning_rate=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])
82
83 # Train the model
84 history = model.fit(
85 X_train_scaled, y_train,
86 validation_data=(X_test_scaled, y_test),
87 epochs=10, # Adjust the number of epochs based on your needs
88 batch_size=32
89 )
90
91 # Evaluate the model
92 loss, accuracy = model.evaluate(X_test_scaled, y_test)
93 print(f"Test accuracy: {accuracy * 100:.2f}%")
94
95 # Save the fine-tuned model
96 model.save('fine_tuned_VGG16_model.h5')
97 return True
98
99# ModelFineTuning() # Uncomment this line to run the training
100 