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
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV, KFold, train_test_split
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'] 

# 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)
# import model packages
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier

# create model dict and param dict
models = {"LogisticRegression":LogisticRegression(),
         "KNeighborsClassifier":KNeighborsClassifier(),
         "DecisionTreeClassifier":DecisionTreeClassifier()}
param_grid = {"LogisticRegression":
              {"LogisticRegression__C": [0.01, 0.1, 1, 10]},
         "KNeighborsClassifier":
              {"KNeighborsClassifier__n_neighbors": range(1, 10)},
         "DecisionTreeClassifier":
              {"DecisionTreeClassifier__max_depth": [2, 5, 10], 
              "DecisionTreeClassifier__min_samples_split": [2, 5, 10, 20],
              "DecisionTreeClassifier__random_state":[42]}
             }
# Gridsearch
pipe_accuracies = {}
pipe_params = {}
pipelines = {}

kf = KFold(n_splits=5, random_state=42, shuffle=True)

for name, model in models.items():
    pipeline = Pipeline(steps=[
        ("scaler", StandardScaler()),
        (name, model)
    ])
    grid_search = GridSearchCV(pipeline, param_grid[name], cv=kf, scoring="accuracy")
    grid_search.fit(X_train, y_train)
    pipe_accuracies[name] = grid_search.best_score_
    pipe_params[name] = grid_search.best_params_
    pipelines[name] = grid_search
best_model_name = max(pipe_accuracies)
best_model_info = pipe_params[best_model_name]
best_model_cv_score = max(pipe_accuracies.values())

print(f"Best model name: {best_model_name}")
print(f"Best model parameters: {best_model_info}")
print(f"Best model CV score: {best_model_cv_score}")
# evaluating best model 

y_pred = pipelines[best_model_name].predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
score = accuracy

print(f"accuracy: {accuracy:.4f}")
print(f"precision: {precision:.4f}")
print(f"recall: {recall:.4f}")
print(f"f1 score: {f1:.4f}")
# confusion matrix
conf_mat = confusion_matrix(y_test, y_pred)
plt.imshow(conf_mat, interpolation="nearest", cmap=plt.cm.Blues)
plt.colorbar()
plt.title(f"Confusion Matrix for {best_model_name}")
plt.xlabel("Predicted Labels")
plt.ylabel("True Labels")
tick_marks = range(len(set(y_test)))
plt.xticks(tick_marks, ["Non-Arnie", "Arnie"], rotation = 90)
plt.yticks(tick_marks, ["Non-Arnie", "Arnie"])
plt.tight_layout()
plt.show()