Skip to content

You are a member of an elite group of data scientists, specialising in advanced facial recognition technology, this firm is dedicated to identifying and safeguarding prominent individuals from various spheres—ranging from entertainment and sports to politics and philanthropy. The team's mission is to deploy AI-driven solutions that can accurately distinguish between images of notable personalities and the general populace, enhancing the personal security of such high-profile individuals. You're to focus on Arnold Schwarzenegger, a figure whose accomplishments span from bodybuilding champion to Hollywood icon, and from philanthropist to the Governor of California.

The Data

The data/lfw_arnie_nonarnie.csv dataset contains processed facial image data derived from the "Labeled Faces in the Wild" (LFW) dataset, focusing specifically on images of Arnold Schwarzenegger and other individuals not identified as him. This dataset has been prepared to aid in the development and evaluation of facial recognition models. There are 40 images of Arnold Schwarzenegger and 150 of other people.

Column NameDescription
PC1, PC2, ... PCNPrincipal components from PCA, capturing key image features.
LabelBinary indicator: 1 for Arnold Schwarzenegger, 0 for others.
# Import required libraries
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV, KFold, train_test_split, cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt

# Read the CSV file 
df = pd.read_csv("data/lfw_arnie_nonarnie.csv")

# Seperate the predictor and class label
X = df.drop('Label', axis=1)
y = df['Label'].astype('bool')

# Split the data into training and testing sets using stratify to balance the class
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=21, stratify=y)
y_test.info()
# Start coding here

# Models: LogisticRegression, KNN, SVC
models = {"LogisticRegression": LogisticRegression(), "KNN": KNeighborsClassifier(), "SVC": SVC()}

# GridSearchCV parameters
models_params = {"LogisticRegression": 
                 {"LogisticRegression__C": np.arange(1,10,1)}, 
                 "KNN": {"KNN__n_neighbors": np.arange(1,11,1)},
"SVC": {"SVC__C": np.arange(0,5,0.1)}}

kf = KFold(n_splits=5, shuffle=True, random_state=42)
best_model_score_parameters = {}
best_scores_model = {}

# loop through each model_name (key) and instantiate (value) in the models dictionary
for model_name, model in models.items():
    steps = [("scaler", StandardScaler()),(model_name, model)]
    model_cv = GridSearchCV(Pipeline(steps),param_grid=models_params[model_name], cv=kf,scoring="accuracy")
    model_cv.fit(X_train,y_train)
    best_model_score_parameters[model_name] = model_cv.best_params_
    best_scores_model[model_name] = model_cv.best_score_

best_model_cv_score = max(best_scores_model.values())
best_model_name = [model_name for model_name, cv_score in best_scores_model.items() if cv_score == best_model_cv_score][0]
best_model_info = best_model_score_parameters[best_model_name]
print(best_model_name)
print(best_model_info)

steps = [("scaler", StandardScaler()),('LogisticRegression', LogisticRegression(C=1))]
best_clf = Pipeline(steps)
best_clf.fit(X_train,y_train)
pred = best_clf.predict(X_test)

accuracy = accuracy_score(y_test,pred)
precision = precision_score(y_test,pred)
recall = recall_score(y_test,pred)
f1 = f1_score(y_test,pred)

print(f"Accuracy: {accuracy}\nPrecision: {precision}\nRecall: {recall}\nF1: {f1}")