<jupyter_start><jupyter_text>Face RecognitionAs an example for image classification, let's take a look at the facial recognition problem. We will use the Labeled Faces in the Wild dataset, which consists of several thousand collated photos of various public figures. A fetcher for the dataset is built into Scikit-Learn:<jupyter_code># Import libs for visualization
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()

# Matrix manipulation
import numpy as np

# Functions for perfomance evaluation and for splitting data
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split

# Load dataset of faces
from sklearn.datasets import fetch_openml
from sklearn.datasets import fetch_lfw_people
faces = fetch_lfw_people(min_faces_per_person=60)
classes = faces.target_names

print('Classes: ',classes)
print('Total classes: ',len(classes))
print('Total images: ',faces.images.shape[0])
print('Image size: ',faces.images[0,:,:].shape)
print('Finished loading.')
mnist = fetch_openml('mnist_784', cache=True)
classes = [str(val) for val in np.unique(mnist.target.astype('int64'))]<jupyter_output><empty_output><jupyter_text>Show some images<jupyter_code>fig, ax = plt.subplots(3, 5)
for i, axi in enumerate(ax.flat):
    axi.imshow(faces.images[i], cmap='bone')
    axi.set(xticks=[], yticks=[],
            xlabel=faces.target_names[faces.target[i]])<jupyter_output><empty_output><jupyter_text>1. Build Linear Support Vector Machine<jupyter_code>from sklearn.svm import SVC
X = mnist.data.astype('float32')
y = mnist.target.astype('int64')
print(X.shape)
print(y.shape)
X = faces.data
y = faces.target
print(X.shape)
print(y.shape)
# Create model
clf = SVC(kernel='linear', C = 1.0)
print('Model built.')

# Train-Test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y,  random_state=42)
print('Data splitted.')

# Fit model
clf.fit(X_train, y_train)
print('Model trained.')<jupyter_output>Model built.
Data splitted.<jupyter_text>Evaluate performance on test<jupyter_code>y_pred = clf.predict(X_test)

# True
print(y_test)
# Prediction
print(y_pred)
print(classification_report(y_test, y_pred, target_names=classes))
mat = confusion_matrix(y_test, y_pred)
sns.heatmap(mat, square=True, annot=True, fmt='d', cbar=False,
            xticklabels=classes,
            yticklabels=classes)
plt.xlabel('Predicted Label')
plt.ylabel('True Label')<jupyter_output><empty_output><jupyter_text>2. Build Linear Support Tensor Machine<jupyter_code>import pystmm
X = mnist.data.astype('float32').reshape(mnist.data.shape[0],28,28)
y = mnist.target.astype('int64')
X.shape, y.shape
len(y[y==5]), len(y[y==6])
X = faces.images
y = faces.target
print(X.shape)
print(y.shape)
# Create model
clf = pystmm.classifier.STMM(typemulticlassifier='ovr',C1=1.0, C2=1.0, maxIter=2, tolSTM=1e-2, penalty = 'l2', dual = True, tol=1e-2,loss = 'squared_hinge', maxIterSVM=100000)
print('Model built.')

# Train-Test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y,  random_state=42)
print('Data splitted.')

# Fit model
clf.fit(X_train, y_train)
print('Model trained.')
y_pred = clf.predict(X_test)
print(classification_report(y_test, y_pred, target_names=classes))
mat = confusion_matrix(y_test, y_pred)
sns.heatmap(mat, square=True, annot=True, fmt='d', cbar=False,
            xticklabels=classes,
            yticklabels=classes)
plt.xlabel('Predicted Label')
plt.ylabel('True Label')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12872666480913902, 'fraction_numerical': 0.01560323209807746, 'mean_word_length': 6.402061855670103, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 20, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '397712', 'license': 'MIT', 'n_tokens_mistral': 1337, 'n_tokens_neox': 1293, 'n_words': 289, 'path': 'examples/Image_Classification.ipynb', 'repo_name': 'cdfbdex/pySTMM', 'size': '3589'}