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 Name | Description |
---|---|
PC1, PC2, ... PCN | Principal components from PCA, capturing key image features. |
Label | Binary 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']
print(df.head())
# 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)
# scale features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
#Design models
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
lreg_clf = LogisticRegression(random_state=42)
sgd_clf = SGDClassifier(random_state=42)
rf_clf = RandomForestClassifier(random_state=42)
kn_clf = KNeighborsClassifier()
models = {"LogisticRegression" : lreg_clf, "SGDClassifier" : sgd_clf, "RandomForestClassifier" : rf_clf, "KNeighborsClassifier": kn_clf}
kf = KFold(n_splits=3,shuffle=True)
params = {'RandomForestClassifier': {'RandomForestClassifier__n_estimators': [100, 500, 700, 1000], 'RandomForestClassifier__max_depth': [None, 1, 2, 3], 'RandomForestClassifier__min_samples_split': [1, 2, 3]},
'LogisticRegression' : {"LogisticRegression__C": [0.01,0.1,1], "LogisticRegression__penalty": ["l2", "l1", "elasticnet"], 'LogisticRegression__max_iter': [10, 50, 100, 1000]},
'SGDClassifier' : {"SGDClassifier__alpha": [0.0001,0.00001,0.001], "SGDClassifier__penalty": ["l2", "l1", "elasticnet"],
'SGDClassifier__max_iter': [10, 50, 80,1000]},
'KNeighborsClassifier' : {"KNeighborsClassifier__n_neighbors": range(1,10)}
}
best_accuracies = {}
best_params = {}
pipelines = {}
for name, model in models.items():
pipeline = Pipeline(steps=[
("scaler", StandardScaler()),
(name, model)
])
# Create the GridSearchCV object
grid_search = GridSearchCV(pipeline, params[name], cv=kf, scoring="accuracy")
# Perform grid search and fit the model and store the results
grid_search.fit(X_train, y_train)
best_accuracies[name] = grid_search.best_score_
best_params[name] = grid_search.best_params_
pipelines[name] = grid_search
best_model_name = max(best_accuracies)
best_model_info = best_params[best_model_name]
best_model_cv_score = best_accuracies[best_model_name]
print('best model: ',best_model_name)
print('best params: ',best_model_info)
print('best score: ',best_model_cv_score)
worst_model = min(best_accuracies)
print('worst model: ', worst_model, 'score: ', best_accuracies[worst_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)
print("Test accuracy: ",accuracy,", precision: ",precision,", recall: ",recall,", f1: ",f1)
score = accuracy