0% found this document useful (0 votes)
6 views3 pages

Facene

The document outlines the process of building a convolutional neural network (CNN) for face recognition using Keras and TensorFlow. It includes steps for data preprocessing, model architecture definition, training the model with image augmentation, and saving the trained model. Additionally, it provides a function for predicting faces from images and an example usage of this function.

Uploaded by

mraut7324
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views3 pages

Facene

The document outlines the process of building a convolutional neural network (CNN) for face recognition using Keras and TensorFlow. It includes steps for data preprocessing, model architecture definition, training the model with image augmentation, and saving the trained model. Additionally, it provides a function for predicting faces from images and an example usage of this function.

Uploaded by

mraut7324
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

# Import required packages

import numpy as np
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten,
BatchNormalization
from keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ReduceLROnPlateau
import matplotlib.pyplot as plt
import cv2
import os

# Define the dataset directory


dataset_dir = 'Images'

# Initialize image data generator with rescaling and augmentation


train_data_gen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest',
validation_split=0.2 # 20% for validation
)

# Preprocess all images (train and validation from the same directory)
train_generator = train_data_gen.flow_from_directory(
dataset_dir,
target_size=(64, 64),
batch_size=32,
color_mode="rgb",
class_mode='categorical',
subset='training', # 80% for training
shuffle=True
)

validation_generator = train_data_gen.flow_from_directory(
dataset_dir,
target_size=(64, 64),
batch_size=32,
color_mode="rgb",
class_mode='categorical',
subset='validation', # 20% for validation
shuffle=True
)

# Define the CNN model


model = Sequential()

# Convolutional layers
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(64, 64,
3)))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))


model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

# Flatten and dense layers


model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(8, activation='softmax')) # 8 persons in your dataset

# Compile the model


model.compile(optimizer=Adam(learning_rate=0.001),
loss='categorical_crossentropy',
metrics=['accuracy'])

# Learning rate reduction callback


reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5,
min_lr=0.00001)

# Train the model


history = model.fit(
train_generator,
steps_per_epoch=train_generator.samples // 32,
epochs=100,
validation_data=validation_generator,
validation_steps=validation_generator.samples // 32,
callbacks=[reduce_lr]
)

# Save the model


model.save('face_recognition_model.weights.h5')

# Plot training results


plt.plot(history.history['accuracy'], label='train_accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend()
plt.show()
"""
# Function to predict a single image (for integration)
def predict_face(image_path, model_path='face_recognition_model.h5'):
# Load the trained model
from keras.models import load_model
model = load_model(model_path)

# Load and preprocess the image


img = cv2.imread(image_path)
img = cv2.resize(img, (64, 64))
img = img / 255.0 # Normalize
img = np.expand_dims(img, axis=0) # Add batch dimension
# Get class labels from the training generator
class_labels = {v: k for k, v in train_generator.class_indices.items()}

# Make prediction
prediction = model.predict(img)
predicted_class = np.argmax(prediction)
confidence = prediction[0][predicted_class]

# Return result
if confidence > 0.7: # Adjustable threshold
return class_labels[predicted_class], confidence
else:
return "Unknown", confidence"""
"""
# Example usage of prediction function
if __name__ == "__main__":
# Test the prediction function with a sample image
test_image_path = 'data/person1/sample_image.jpg' # Replace with an actual
image path
if os.path.exists(test_image_path):
name, confidence = predict_face(test_image_path)
print(f"Predicted: {name} with confidence {confidence:.2f}")
else:
print("Test image not found. Provide a valid image path to test the
prediction.")"""

You might also like