Data Reduction, Normalization, and Discretization

Overview

We assume that you work on Google Colab. If you are using a different IDE, then you should pay attention to the parts that needs modifications before you write your code.

For most of the parts, we are going to use the raisin. We will also use the preprocessing module from sklearn package for performing most of the tasks. For the affinity gap similarity, it is highly recommended to use the Biopython Package.

%pip install -q biopython jellyfish

Now, we import the required libraries that will be used to solve the exercises.

import pandas as pd
import numpy as np

from sklearn.preprocessing import MinMaxScaler as mms
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from Bio.Align import PairwiseAligner
import requests
from io import StringIO
from IPython.display import display
from random import shuffle
from itertools import combinations
from numpy.testing import assert_array_almost_equal

1. Data Reduction

For the following exercises, we will use the Rainsin Dataset. We will start by creating a pandas dataframe by reading the dataset.

Note: the dataset is in 'XLSX' format.

df = pd.read_excel('./sample_data/Raisin_Dataset.xlsx')
original_df = df.copy()
df.head()
Dataset at a glance

Look for: class balance, feature ranges, and possible scale differences.

fig, ax = plt.subplots(1, 2, figsize=(12, 4))
df.iloc[:, -1].value_counts().plot.bar(ax=ax[0], color=['#2563eb','#f59e0b'])
ax[0].set(title='Raisin classes', xlabel='Class', ylabel='Number of records')
df.select_dtypes('number').boxplot(ax=ax[1], rot=55)
ax[1].set(title='Original feature scales', ylabel='Value')
plt.tight_layout(); plt.show()
3.1 Sampling

To select a random subset without replacement, one way is to slice off the first k elements of the array returned by permutation, where k is the desired subset size. Here, we use the 'take' method, which retrieves elements along a given axis at the given indices. Using this function, we slice off the first three elements:

df_sampled_without_replacement = df.take(np.random.permutation(len(df))[:3])
df_sampled_without_replacement
df.sample(frac=1).take(range(0,3))

To generate a sample with replacement, we can draw random integers and put the 'replace' to 'True'.

df.sample(n = 3, replace = True)

OR you can generate a set of random integer samples of size three

These random integers can be used as input for the 'take' method, which is then used to sample the data. Since the random integers consistuting the array may be repeated, the rows sampled by this method may also be repeated -- or, in other words, sampled with replacement.

sampler = np.random.randint(0, len(df), size=3)
df.take(sampler)
df = pd.DataFrame(np.arange(5 * 4). reshape(5, 4), index = ['een', 'twee', 'drie', 'vier', 'vijf'])
df_sampled_without_replacement = df.take(np.random.permutation(len(df))[:3])
df_sampled_without_replacement
Sampling changes what we see

Without replacement: every selected row is unique. With replacement: a row can appear more than once.

rng = np.random.default_rng(42)
fig, axes = plt.subplots(1, 2, figsize=(11, 3))
for ax, replace, title in zip(axes, [False, True], ['Without replacement', 'With replacement']):
    chosen = rng.choice(np.arange(12), size=9, replace=replace)
    ax.scatter(np.arange(9), chosen, s=110, c=chosen, cmap='viridis', vmin=0, vmax=11)
    ax.set(xlabel='Draw number', ylabel='Original row ID', title=title, yticks=range(12))
    ax.grid(alpha=.2)
plt.tight_layout(); plt.show()
3.2 Principal Component Analysis

Re-read the dataset again.

df_raisin = original_df
df_raisin

PCA is affected by scale so you need to scale the features in your data before applying PCA. Use StandardScaler to help you standardize the dataset’s features (mean = 0 and variance = 1) which is a requirement for the optimal performance of many machine learning algorithms.

from sklearn.preprocessing import StandardScaler as ss

df_raisin_n = df_raisin.drop(columns = df_raisin.columns[-1])
x = df_raisin_n.values
x = ss().fit_transform(x)
x
Why scale before PCA?

PCA follows directions of high variance. A feature measured in larger units can dominate those directions.

fig, ax = plt.subplots(1, 2, figsize=(12, 4))
df_raisin_n.boxplot(ax=ax[0], rot=50)
ax[0].set(title='Before scaling', ylabel='Original units')
pd.DataFrame(x, columns=df_raisin_n.columns).boxplot(ax=ax[1], rot=50)
ax[1].set(title='After StandardScaler', ylabel='Standard deviations')
plt.tight_layout(); plt.show()

Original data has more than two columns (execluding the class label column), we would like to project the data into 2 dimensional data

pca = PCA(n_components = 2)               # You can also use pca = PCA(2)
pcs = pca.fit_transform(x)
pcsDF = pd.DataFrame(data = pcs, columns = ['PC1', 'PC2'])
[Exercise] Does scaling change PCA?

Problem: PCA identifies directions of maximum variance. Do features with large numerical units influence those directions?

Your task: Run the comparison below, then change use_scaling from True to False in the experiment cell.

Hints - what to look for:

  • Which projection separates the two raisin classes more clearly?

  • How do the percentages of variance explained by PC1 and PC2 change?

  • Are the units of the features affecting the result?

use_scaling = False  # Change to False

X_experiment = x if use_scaling else df_raisin_n.values

model = PCA(n_components=2)
projection = model.fit_transform(X_experiment)

classes = df_raisin.iloc[:, -1].astype('category').cat.codes

plt.figure(figsize=(7, 5))
plt.scatter(projection[:, 0], projection[:, 1],
            c=classes, cmap='coolwarm', s=15, alpha=0.6)

plt.title(f"PCA {'with' if use_scaling else 'without'} Standardization")
plt.xlabel(f"PC1 ({model.explained_variance_ratio_[0]:.1%})")
plt.ylabel(f"PC2 ({model.explained_variance_ratio_[1]:.1%})")
plt.colorbar(label="Class")
plt.show()
PCA: view the same records in 2D

Each dot is a raisin, color shows its known class.

[Question] Do the two classes separate?

#  PCA on the Raisin dataset

pca = PCA(n_components=2)
pcs = pca.fit_transform(x)
labels = df_raisin.iloc[:, -1].astype('category')

fig, ax = plt.subplots(figsize=(8, 6))
for name in labels.cat.categories:
    mask = (labels == name).to_numpy()
    ax.scatter(pcs[mask, 0], pcs[mask, 1],
               s=20, alpha=0.65, label=str(name))
ax.set(
    xlabel=f'PC1 ({pca.explained_variance_ratio_[0]:.1%} variance)',
    ylabel=f'PC2 ({pca.explained_variance_ratio_[1]:.1%} variance)',
    title='PCA Projection — Raisin Dataset'
)

ax.legend()
plt.show()

Extract and display the eigenvectors, eigenvalues. Note that we already eliminated the PCs with small eigenvalues. We only extraced two PCs.

eigenvectors, eigenvalues = pca.components_, pca.explained_variance_
eigenvectors, eigenvalues

We can also start by computing all the PCs and discard the ones that are not required later.

PCs = []
for i in range(len(df_raisin_n.columns)):
    s = 'PC'+str(i+1)
    PCs.append(s)
pca1 = PCA(n_components = len(df_raisin_n.columns))
pcs1 = pca1.fit_transform(x)
pcsDF1 = pd.DataFrame(data = pcs1, columns = PCs)
# Comparing the two methods
pcsDF_red = pcsDF1[['PC1', 'PC2']]
assert_array_almost_equal(pcsDF, pcsDF_red)

We can plot the values of the eigenvalues and make sure that the discarded components have eigenvalues smaller than 1.

eigenvectors1, eigenvalues1 = pca1.components_, pca1.explained_variance_
plt.bar(np.array(range(len(df_raisin_n.columns))), eigenvalues1, color = 'green')
plt.xticks(np.array(range(len(df_raisin_n.columns))), PCs)
plt.show()
How many components do we need?

The cumulative curve shows how much total variance is retained as we keep more components.

ratios = pca1.explained_variance_ratio_
fig, ax = plt.subplots(figsize=(8, 4))
ax.bar(np.arange(1, len(ratios)+1), ratios, alpha=.5, label='Individual')
ax.plot(np.arange(1, len(ratios)+1), np.cumsum(ratios), 'o-', label='Cumulative')
ax.axhline(.9, ls='--', color='gray', label='90% variance')
ax.set(xlabel='Number of principal components', ylabel='Explained variance ratio', ylim=(0, 1.05), title='PCA variance retained')
ax.legend(); plt.tight_layout(); plt.show()

We can also plot the projected data on the two components with the eigenvectors in the same plot to see the directions of the eigenvectors. An example code can be found here.

fig, ax = plt.subplots(figsize=(10,10))
ax.scatter(pcsDF1["PC1"], pcsDF1["PC2"])
K = 2
mu = pcs1.mean(axis=0)

i = 1
for axis, color in zip(eigenvectors1[:K], ["red","green"]):
    start, end = (mu)[:K], (mu + 2 * eigenvalues1[i-1] * axis)[:K]
    pc = 'PC' + str(i)
    ax.arrow(start[0], start[1], end[0], end[1], head_width=0.2, head_length=0.3, fc = color, ec = color)
    ax.annotate(pc, (end[0] + 0.05 * eigenvalues1[i-1], end[1] + 0.05 * eigenvalues1[i-1]),fontsize = 14)
    i += 1


ax.set_aspect('equal')
plt.show()
[Exercise] Beyond PCA: nonlinear embeddings
  • LLE and Isomap preserve local geometry

  • t-SNE emphasizes local neighborhoods.

Distances between distant t-SNE clusters should not be overinterpreted.

Find the implementations of LLE, Isomap and t-SNE from sklearn and use them in a similar way like we did with PCA.

# TODO
3D PCA: rotate the projection

The third component adds another direction of variation; compare it with the 2D view.

PCA geometry

Key idea: PCA does not simply remove an original feature. It finds a rotated plane that captures the largest variation. The dots below are shown in three principal-component coordinates, the translucent plane is where they land when PC3 is discarded.

from mpl_toolkits.mplot3d import Axes3D
pca_plane = PCA(n_components=3).fit(x)
xyz = pca_plane.transform(x)
fig = plt.figure(figsize=(9, 6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xyz[:, 0], xyz[:, 1], xyz[:, 2], c=df_raisin.iloc[:, -1].astype('category').cat.codes, cmap='coolwarm', s=10, alpha=.28)
xx, yy = np.meshgrid(np.linspace(xyz[:,0].min(),xyz[:,0].max(),12), np.linspace(xyz[:,1].min(),xyz[:,1].max(),12))
ax.plot_surface(xx, yy, np.zeros_like(xx), alpha=.18, color='steelblue')
ax.set(xlabel='PC1', ylabel='PC2', zlabel='PC3', title='PCA projection plane (PC3 = 0)')
plt.show()
from mpl_toolkits.mplot3d import Axes3D
pcs3 = PCA(n_components=3).fit_transform(x)
fig = plt.figure(figsize=(9, 6)); ax = fig.add_subplot(111, projection='3d')
for name in labels.cat.categories:
    mask = (labels == name).to_numpy()
    ax.scatter(pcs3[mask,0], pcs3[mask,1], pcs3[mask,2], s=12, alpha=.55, label=str(name))
ax.set(xlabel='PC1', ylabel='PC2', zlabel='PC3', title='Three principal components')
ax.legend(); plt.show()

Now, let's apply the same concept on synthetic data from two dimensional normal distribution

mean = [1, 1]
cov = [[1, 0.9], [0.9, 1]]
db = np.random.multivariate_normal(mean, cov, 5000).T
db = db.transpose()
syntheticDF = pd.DataFrame(data = db, columns = ['x', 'y'])
plt.plot(syntheticDF['x'], syntheticDF['y'], 'x')
plt.axis('equal')
plt.show()

Synthetic PCA: fit two principal components to the 2D correlated points, then draw the principal directions on the original coordinates.

pca = PCA(n_components=2)
pcs = pca.fit_transform(syntheticDF)

Extract and display the eigenvalues, eigenvectors

eigenvalues = pca.explained_variance_
eigenvectors = pca.components_

print("Eigenvalues:", eigenvalues)
print("Eigenvectors:", eigenvectors)

Plot the original data with the eigenvectors

plt.figure(figsize=(8, 8))
plt.scatter(syntheticDF['x'], syntheticDF['y'], alpha=0.2)

mu = pca.mean_

for i in range(2):
    vector = eigenvectors[i] * 2 * np.sqrt(eigenvalues[i])
    plt.arrow(mu[0], mu[1], vector[0], vector[1],
              width=0.02, label=f'PC{i+1}')

plt.axis('equal')
plt.legend()
plt.show()
PCA as geometry

The longer arrow points along the direction with greater variance. PCA rotates the coordinate system; it does not change the original points.

from matplotlib.patches import Ellipse
fig, ax = plt.subplots(figsize=(7, 6))
ax.scatter(syntheticDF['x'], syntheticDF['y'], s=6, alpha=.12)
for i, (direction, value) in enumerate(zip(eigenvectors, eigenvalues)):
    arrow = direction * 2 * np.sqrt(value)
    ax.annotate('', xy=mu+arrow, xytext=mu, arrowprops=dict(arrowstyle='->', lw=3))
    ax.text(*(mu+arrow*1.08), f'PC{i+1}', fontsize=12, weight='bold')
ax.set(xlabel='Original x', ylabel='Original y', title='Principal directions in the original space')
ax.axis('equal'); ax.grid(alpha=.2); plt.show()
[Exercise] Correlation Analysis

Fill in one line the correlation implementation from pandas

corr_mat = # YOUR CODE
corr_mat
Correlation heatmap

+1: strong positive linear relationship. −1: strong negative relationship. 0: little linear relationship.

fig, ax = plt.subplots(figsize=(8, 6))
im = ax.imshow(corr_mat, vmin=-1, vmax=1, cmap='coolwarm')
ax.set(xticks=range(len(corr_mat)), yticks=range(len(corr_mat)),
       xticklabels=corr_mat.columns, yticklabels=corr_mat.index, title='Feature correlations')
plt.setp(ax.get_xticklabels(), rotation=45, ha='right')
for i in range(len(corr_mat)):
    for j in range(len(corr_mat)):
        ax.text(j, i, f'{corr_mat.iloc[i,j]:.2f}', ha='center', va='center', fontsize=8)
fig.colorbar(im, ax=ax, shrink=.8); plt.tight_layout(); plt.show()

2. Data Transformation (Normalization or Standardization)

We begin by defining a pandas dataframe that contains some cells with missing values. Note that pandas, in addition to allowing us to create dataframes from a variety of files, also supports explicit declaration.

Create dataframe
df_raisin = original_df
df_raisin
df_raisin.columns
df_raisin_n = df_raisin.drop(columns = df_raisin.columns[-1])
df_raisin_n
[Exercise] Normalize the data such that the summation of the values in each attribute (column) is 1.
# TODO

Verify (all should be equal to 1.0)

for c in df_norm.columns:
    print(c, df_norm[c].sum())
Min-Max Normalization to [-5, 5]

Min-Max normalization rescales each numerical feature to a specified range while preserving the relative distances between values.

The transformation is:

$$ x' = \frac{x - x_{\min}}{x_{\max} - x_{\min}}(b-a) + a $$

where:

  • $x_{\min}, x_{\max}$: Minimum and maximum values of the original feature.

  • $a, b$: Lower and upper bounds of the new range (here, -5 and 5).

[Exercise] Implement Min-Max normalization and apply it to each column, mapping its values to the interval [-5, 5].
def normalizeMM(values, new_min, new_max):
    return # TODO

new_min = -5
new_max = 5
new_df_MM = df_raisin_n.copy()
for C in new_df_MM.columns:
    new_df_MM[C] = normalizeMM(new_df_MM[C], new_min, new_max)
new_df_MM

or use a sklearn implementation:

# define min max scaler
scalerMM = mms(feature_range=(-5, 5))

# transform data
scaledMM = scalerMM.fit_transform(df_raisin_n)
scaledMMDF = pd.DataFrame(scaledMM, columns = df_raisin_n.columns)
scaledMMDF
Min–Max scaling: the shape remains

Only the units and endpoints change. The order of observations is preserved.

feature = df_raisin_n.columns[0]
fig, ax = plt.subplots(1, 2, figsize=(11, 4))
ax[0].hist(df_raisin_n[feature], bins=25, color='#2563eb', alpha=.8)
ax[1].hist(new_df_MM[feature], bins=25, color='#f59e0b', alpha=.8)
ax[0].set(title=f'{feature}: original', xlabel='Original units')
ax[1].set(title=f'{feature}: mapped to [-5, 5]', xlabel='Scaled units')
for a in ax: a.set_ylabel('Count')
plt.tight_layout(); plt.show()
new_df_MM.equals(scaledMMDF)

Numerical check: exact DataFrame equality can fail due to floating-point rounding; use np.allclose for approximate agreement.

for C in new_df_MM:
    diff = (new_df_MM[C] - scaledMMDF[C]).sum()
    print('Difference in column (', C, ') = ', diff)

Standardize features (columns) by removing the mean and scaling to unit variance.

The standard score of a sample $x$ is calculated as:

$$z = \frac{(x - \mu)}{\sigma}$$

Where $\mu$ is the mean of the values in $x$ and $\sigma$ is the standard deviation. The new data should have a mean of 0 and a standard deviation of 1.

new_df_SS = df_raisin_n.copy()
for C in new_df_SS.columns:
    new_df_SS[C] = (new_df_SS[C] - new_df_SS[C].mean()) / new_df_SS[C].std(ddof=0)
new_df_SS
scalerSS = ss()
scaledSS = scalerSS.fit_transform(df_raisin_n)
scaledSSDF = pd.DataFrame(scaledSS, columns = df_raisin_n.columns)
scaledSSDF
np.allclose(new_df_SS, scaledSSDF)
np.allclose(new_df_SS, scaledSSDF)
Standardization: centered at zero

StandardScaler: subtract each column mean, then divide by its standard deviation. Unlike Min–Max scaling, it does not set fixed bounds.

feature = scaledSSDF.columns[0]
fig, ax = plt.subplots(figsize=(8, 4))
ax.hist(scaledSSDF[feature], bins=30, alpha=.75, color='#2563eb')
ax.axvline(0, ls='--', color='black', label='Mean = 0')
ax.axvline(-1, ls=':', color='#dc2626', label='±1 standard deviation')
ax.axvline(1, ls=':', color='#dc2626')
ax.set(title=f'Standardized {feature}', xlabel='Z-score', ylabel='Count')
ax.legend(); plt.tight_layout(); plt.show()

Important: StandardScaler uses population standard deviation (ddof=0).

3. Entity Resolution - measuring similarity

Goal: identify records referring to the same entity, even when names contain typos, reordered characters, or abbreviations.

We use library implementations rather than implementing string matching algorithms from scratch.

Dependencies: jellyfish and biopython (install with %pip install jellyfish biopython if missing).

import jellyfish
from Bio.Align import PairwiseAligner

ldist = jellyfish.levenshtein_distance
jaro_sim = jellyfish.jaro_similarity
jaro_winkler = jellyfish.jaro_winkler_similarity

def affine_gap_distance(s1, s2, mismatch=-2, open_gap=-1, gap_ext=-0.1):
    aligner = PairwiseAligner()
    aligner.mode = "global"
    aligner.match_score = 0
    aligner.mismatch_score = mismatch
    aligner.open_gap_score = open_gap
    aligner.extend_gap_score = gap_ext
    return round(-aligner.score(s1, s2), 2)

s1 = "Advances in Instrumentation and Control"
s2 = "Adv. Instrum. Control"
print("Affine-gap distance:", affine_gap_distance(s1, s2))
s1, s2 = "MARTHA", "MARHTA"
print("Levenshtein distance:", ldist(s1, s2))
print("Jaro similarity:", round(jaro_sim(s1, s2), 4))
print("Jaro–Winkler similarity:", round(jaro_winkler(s1, s2), 4))
def aff_sim(s1, s2, mismatch=-2, open_gap=-1, gap_ext=-0.1):
    return 1 - affine_gap_distance(s1, s2, mismatch, open_gap, gap_ext) / max(len(s1), len(s2), 1)
data_columns = ['pub_id', 'title', 'authors', 'conf', 'year']
data1 = [375678,"Adaptable query optimization and evaluation in temporal middleware",\
         "Giedrius Slivinskas, Christian S. Jensen, Richard Thomas Snodgrass",\
         "International Conference on Management of Data",2001]
data2 = ["SlivinskasJS01","Adaptable Query Optimization and Evaluation in Temporal Middleware",\
         "Christian S. Jensen, Richard T. Snodgrass, Giedrius Slivinskas","SIGMOD Conference", 2001]


def Lev_sim(s1, s2):
    return 1 - ldist(s1, s2) / max(len(s1), len(s2), 1)

def mod_jaro_sim(s1, s2):
    if  str(s1) == 'nan' and str(s2) == 'nan':
        return 1
    if str(s1) == 'nan':
        return 0
    if str(s2) == 'nan':
        return 0

    j_sim = jaro_sim (s1, s2)
    return j_sim

def record_sim(rec1, rec2, threshold):
    s_t = Lev_sim(rec1[1], rec2[1])
    s_a = mod_jaro_sim (rec1[2], rec2[2])
    s_c = aff_sim (rec1[3], rec2[3], 1, 0.1)
    s_y = 1 if rec1[4] == rec2[4] else 0

    rec_sim = 0.5 * s_t + 0.2 * s_a + 0.2 * s_c + 0.1 * s_y
    print ("the similarity between the two records = ", rec_sim)
    if rec_sim > threshold:
        return True
    else: return False

record_sim(data1, data2, 0.7)
[Exercise] Which similarity measure works best?

Problem: Typos, transpositions, and abbreviations change strings in different ways. One similarity measure may not work equally well for all of them.

Your task: Add one string pair to pairs below, then compare the three measures.

Hints - what to look for:

  • Which measure handles swapped letters best?

  • Does a shared prefix influence Jaro–Winkler?

  • Remember: Levenshtein is a distance (lower is better), while Jaro and Jaro–Winkler are similarities (higher is better).

import jellyfish

# pairs = [('Martha', 'Marhta'), ('Data Science', 'Data Sciences'), ('International Conference', 'Intl. Conf.')]
pairs = [] # TODO
rows = []
for a, b in pairs:
    rows.append([f'{a} / {b}', jellyfish.levenshtein_distance(a,b),
                 jellyfish.jaro_similarity(a,b), jellyfish.jaro_winkler_similarity(a,b)])
metric_df = pd.DataFrame(rows, columns=['Pair','Edit distance ↓','Jaro ↑','Jaro-Winkler ↑']).set_index('Pair')
display(metric_df.round(3))
metric_df[['Jaro ↑','Jaro-Winkler ↑']].plot.barh(figsize=(9,3), xlim=(0,1), title='Similarity depends on the metric')
plt.tight_layout(); plt.show()
Entity resolution: combine imperfect clues

A title, author, venue, or year may disagree slightly. A weighted similarity score combines evidence before deciding whether two records match.

Similarity heatmap - Which strings are plausible matches?

Key idea: Similarity depends on the metric and the kind of variation. The diagonal should always be 1; look for high scores off the diagonal.

names = ['Martha', 'Marhta', 'Maria', 'Data Science', 'Data Sciences', 'Data Eng.']
S = np.array([[jellyfish.jaro_winkler_similarity(a, b) for b in names] for a in names])
fig, ax = plt.subplots(figsize=(8, 5))
im = ax.imshow(S, vmin=0, vmax=1, cmap='YlGnBu')
ax.set(xticks=range(len(names)), yticks=range(len(names)), xticklabels=names, yticklabels=names, title='Jaro–Winkler similarity')
plt.setp(ax.get_xticklabels(), rotation=40, ha='right')
for i in range(len(names)):
    for j in range(len(names)):
        ax.text(j, i, f'{S[i,j]:.2f}', ha='center', va='center', fontsize=8, color='white' if S[i,j]>.65 else 'black')
fig.colorbar(im, ax=ax, label='Similarity'); plt.tight_layout(); plt.show()
weights = pd.Series({'Title':.5, 'Authors':.2, 'Conference':.2, 'Year':.1})
fig, ax = plt.subplots(figsize=(7, 3))
ax.barh(weights.index[::-1], weights.values[::-1], color=['#94a3b8','#60a5fa','#2563eb','#1d4ed8'])
ax.set(xlim=(0,.55), xlabel='Weight in record similarity', title='Which fields influence the decision?')
for j, v in enumerate(weights.values[::-1]): ax.text(v+.01, j, f'{v:.0%}', va='center')
plt.tight_layout(); plt.show()
Locality Sensitive Hashing (LSH)

In the realm of large datasets and high-dimensional spaces, searching for items can be computationally challenging. Specifically, if you want to find items that are similar to a given item (known as the "query item"), conventional search methods might take an impractical amount of time. This is especially true for tasks like finding similar documents in a vast collection of text or similar image in a massive image database.

Enter Locality Sensitive Hashing (LSH), an ingenious technique designed to tackle such problems.

The Core Concept

Imagine you have vast collection of images and you want to find all documents similar to a particular one. If you've applied LSH to our documents, instead of comparing the query to every single document in the collection, you'd only need to compare it with documents in same hash bucket. At its heart, LSH is a method for hashing data points in such a way that similar data points will, with high probability, end up in the same "bucket" or hash bin. Conversely, dissimilar items will, with high probability, end up in different bins.

Hashing.png

Unlike traditional hash functions used in dictionaries, which aim to reduce the likelihood of multiple key-values mapping to the same bucket, LSH operates differently. In dictionary hashing, minimizing collisions is crucial. On the contrary, LSH actively embraces collisions, especially for similar inputs. The essence of an LSH function is to group like values into identical buckets.

While the core principle of LSH is to bucket similar items using a hash function, the methodologies can differ significantly.

The technique we're introducing, and which will be the point of this lab, is based on established methods involving shingling, MinHashing, and banding.

Loading data set

First we need data set. There are great repository in internet for testing similarity search testing. We will be extracting a set of sentences from here.

url = "https://raw.githubusercontent.com/brmson/dataset-sts/master/data/sts/sick2014/SICK_train.txt"
response = requests.get(url)
if response.status_code == 200:
    content = response.text
    df_docs = pd.read_csv(StringIO(content), delimiter='\t')
    display(df_docs)
else:
    print("Failed to fetch data from the URL.")
Shingling, MinHashing, and LSH

The Locality-Sensitive Hashing (LSH) approach encompasses a three-step process. Initially, we convert text into sparse vectors using k-shingling and one-hot encoding. We then employ minhashing to generate 'signatures,' which are subsequently used in our LSH process to filter out potential candidate pairs. Finally, we group the signatures into buckets where each bucket conatins the set of doocuments that are potentially similar. This will reduce the computational cost as the pairwise similarity will be performed only on the documents with signatures falling in the same bucket. If the number of buckets is large enough and the signatures are evenly distributed among the buckets, the computational cost will be reduced significantly.

k-Shingling

k-Shingling, often referred to as shingling, involves the transformation of a text string into a collection of 'shingles'. This procedure resembles sliding a window of length k along our text string and capturing a snapshot at each step. We aggregate all these snapshots to form our set of shingles.

def shingle(text: str, k: int)->set:
    """
    Create a set of 'shingles' from the input text using k-shingling.

    Parameters:
        text (str): The input text to be converted into shingles.
        k (int): The length of the shingles (substring size).

    Returns:
        set: A set containing the shingles extracted from the input text.
    """
    shingle_set = []
    for i in range(len(text) - k+1):
        shingle_set.append(text[i:i+k])
    return set(shingle_set)

def build_vocab(shingle_sets: list)->dict:
    """
    Constructs a vocabulary dictionary from a list of shingle sets.

    This function takes a list of shingle sets and creates a unified vocabulary
    dictionary. Each unique shingle across all sets is assigned a unique integer
    identifier.

    Parameters:
    - shingle_sets (list of set): A list containing sets of shingles.

    Returns:
    - dict: A vocabulary dictionary where keys are the unique shingles and values
      are their corresponding unique integer identifiers.

    Example:
    sets = [{"apple", "banana"}, {"banana", "cherry"}]
    build_vocab(sets)
    {'apple': 0, 'cherry': 1, 'banana': 2}  # The exact order might vary due to set behavior
    """
    full_set = {item for set_ in shingle_sets for item in set_}
    vocab = {}
    for i, shingle in enumerate(list(full_set)):
        vocab[shingle] = i
    return vocab

def one_hot(shingles: set, vocab: dict):
    vec = np.zeros(len(vocab))
    for shingle in shingles:
        idx = vocab[shingle]
        vec[idx] = 1
    return vec
Use shingling on the set of document in the dataframe df_docs
k = 3
sentences = df_docs['sentence_A'].tolist()
sentences.extend(df_docs['sentence_B'].tolist())
print(f"the number of sentences (documents):{len(sentences)}")
shingles = []
for sentence in sentences:
    shingles.append(shingle(sentence,k))
vocab = build_vocab(shingles)
print(f"Number of vocabulary is:{len(vocab)}")
shingles_1hot = []
for shingle_set in shingles:
    shingles_1hot.append(one_hot(shingle_set,vocab))
shingles_1hot = np.stack(shingles_1hot)
shingles_1hot
Shingling turns text into sets

Two strings are similar when many of their k-character shingles overlap. Jaccard similarity = intersection / union.

a, b = shingles[2], shingles[3]
fig, ax = plt.subplots(figsize=(7, 3))
counts = [len(a-b), len(a&b), len(b-a)]
ax.bar(['Only A', 'Shared', 'Only B'], counts, color=['#60a5fa','#16a34a','#f59e0b'])
ax.set(ylabel='Number of shingles', title=f'3-shingle overlap • Jaccard = {len(a&b)/max(1,len(a|b)):.2f}')
plt.tight_layout(); plt.show()
MinHashing

Minhashing is represents the task of transforming the sparse vectors (in the documents-shingles matrix) into dense ones. Starting with the sparse vectors, for each slot in the signature, we randomly produce a single minhash function. For instance, if we aim to formulate a dense vector or signature with 20 values, we would deploy 20 hashing functions.

These hashing functions generate sequences of numbers arranged in randomly. We sequentially number them from 1 up to the number of shingles (vocab entries).

def get_minhash_arr(num_hashes:int,vocab:dict):
    """
    Generates a MinHash array for the given vocabulary.

    This function creates an array where each row represents a hash function and
    each column corresponds to a word in the vocabulary. The values are permutations
    of integers representing the hashed value of each word for that particular hash function.

    Parameters:
    - num_hashes (int): The number of hash functions (rows) to generate for the MinHash array.
    - vocab (dict): The vocabulary where keys are words and values can be any data
      (only keys are used in this function).

    Returns:
    - np.ndarray: The generated MinHash array with `num_hashes` rows and columns equal
      to the size of the vocabulary. Each cell contains the hashed value of the corresponding
      word for the respective hash function.

    Example:
    vocab = {'apple': 1, 'banana': 2}
    get_minhash_arr(2, vocab)
    # Possible output:
    # array([[1, 2],
    #        [2, 1]])
    """
    length = len(vocab.keys())
    arr = np.zeros((num_hashes,length))
    for i in range(num_hashes):
        permutation = np.random.permutation(len(vocab.keys())) + 1
        arr[i,:] = permutation.copy()
    return arr.astype(int)

def get_signature(minhash:np.ndarray, vector:np.ndarray):
    """
    Computes the signature of a given vector using the provided MinHash matrix.

    The function finds the nonzero indices of the vector, extracts the corresponding
    columns from the MinHash matrix, and computes the signature as the minimum value
    across those columns for each row of the MinHash matrix.

    Parameters:
    - minhash (np.ndarray): The MinHash matrix where each column represents a shingle
      and each row represents a hash function.
    - vector (np.ndarray): A vector representing the presence (non-zero values) or
      absence (zero values) of shingles.

    Returns:
    - np.ndarray: The signature vector derived from the MinHash matrix for the provided vector.

    Example:
    minhash = np.array([[2, 3, 4], [5, 6, 7], [8, 9, 10]])
    vector = np.array([0, 1, 0])
    get_signature(minhash, vector)
    output:array([3, 6, 9])
    """
    idx = np.nonzero(vector)[0].tolist()
    shingles = minhash[:,idx]
    signature = np.min(shingles,axis=1)
    return signature

def jaccard_similarity(set1, set2):
    intersection_size = len(set1.intersection(set2))
    union_size = len(set1.union(set2))
    return intersection_size / union_size if union_size != 0 else 0.0

def compute_signature_similarity(signature_1, signature_2):
    """
    Calculate the similarity between two signature matrices using MinHash.

    Parameters:
    - signature_1: First signature matrix as a numpy array.
    - signature_matrix2: Second signature matrix as a numpy array.

    Returns:
    - Estimated Jaccard similarity.
    """
    # Ensure the matrices have the same shape
    if signature_1.shape != signature_2.shape:
        raise ValueError("Both signature matrices must have the same shape.")
    # Count the number of rows where the two matrices agree
    agreement_count = np.sum(signature_1 == signature_2)
    # Calculate the similarity
    similarity = agreement_count / signature_2.shape[0]

    return similarity
minhash_arr =  get_minhash_arr(100,vocab)
signatures = []
for vector in shingles_1hot:
    signatures.append(get_signature(minhash_arr,vector))
signatures = np.stack(signatures)
signatures.shape
MinHash compresses sets into signatures

Instead of comparing thousands of shingle indicators, compare a short signature. The fraction of matching signature entries estimates Jaccard similarity.

fig, ax = plt.subplots(figsize=(9, 4))
view = signatures[:15, :30]
ax.imshow(view, aspect='auto', cmap='viridis')
ax.set(xlabel='Hash function', ylabel='Document', title='MinHash signatures (15 documents × 30 hashes)')
plt.tight_layout(); plt.show()
print(compute_signature_similarity(signatures[2],signatures[3]))
print(jaccard_similarity(shingles[3],shingles[2]))
Final Step: LSH Function (Optional)

After preparing the data using the methods mentioned above, the LSH function is applied. This function divides the MinHash signature of each sentence into multiple bands and hashes each band. If two sentences have the same hash value for any band, they are considered to be potentially similar and are placed in the same bucket. Sentences within the same bucket are then checked more thoroughly to determine the degree of their similarity. By adjusting parameters like the number of bands and rows, one can control the trade-off between precision and recall.

class LSH:
    """
    Implements the Locality Sensitive Hashing (LSH) technique for approximate
    nearest neighbor search.
    """

    def __init__(self, b: int):
        """
        Initializes the LSH instance with a specified number of bands.

        Parameters:
        - b (int): The number of bands to divide the signature into.
        """
        self.b = b
        self.buckets = []
        self.counter = 0
        for i in range(b):
            self.buckets.append({})

    def make_subvecs(self, signature: np.ndarray) -> np.ndarray:
        """
        Divides a given signature into subvectors based on the number of bands.

        Parameters:
        - signature (np.ndarray): The MinHash signature to be divided.

        Returns:
        - np.ndarray: A stacked array where each row is a subvector of the signature.
        """
        l = len(signature)
        assert l % self.b == 0
        r = int(l / self.b)
        subvecs = []
        for i in range(0, l, r):
            subvecs.append(signature[i:i+r])
        return np.stack(subvecs)

    def add_hash(self, signature: np.ndarray):
        """
        Adds a signature to the appropriate LSH buckets based on its subvectors.

        Parameters:
        - signature (np.ndarray): The MinHash signature to be hashed and added.
        """
        subvecs = self.make_subvecs(signature).astype(str)
        for i, subvec in enumerate(subvecs):
            subvec = ','.join(subvec)
            if subvec not in self.buckets[i].keys():
                self.buckets[i][subvec] = []
            self.buckets[i][subvec].append(self.counter)
        self.counter += 1

    def check_candidates(self) -> set:
        """
        Identifies candidate pairs from the LSH buckets that could be potential near duplicates.

        Returns:
        - set: A set of tuple pairs representing the indices of candidate signatures.
        """
        candidates = []
        for bucket_band in self.buckets:
            keys = bucket_band.keys()
            for bucket in keys:
                hits = bucket_band[bucket]
                if len(hits) > 1:
                    candidates.extend(combinations(hits, 2))
        return set(candidates)
b = 10
lsh = LSH(b)
for signature in signatures:
    lsh.add_hash(signature)
candidate_pairs = lsh.check_candidates()
len(candidate_pairs)
[Exercise] Tune the LSH bands

Problem: Comparing every document pair is expensive. LSH generates fewer candidate pairs, but may miss some genuinely similar pairs.

Your task: Change band_options in the next cell (use divisors of 100, e.g., 4, 5, 10, 20, 25) and rerun the plots.

Hints - what to look for:

  • Does increasing the number of bands produce more or fewer candidate pairs?

  • What happens to the probability of retrieving a pair with similarity $s=0.8$?

  • With 100 signature entries, each band contains $r=100/b$ rows: $P(\mathrm{candidate})=1-(1-s^r)^b$.

band_options = [5, 10, 20, 25]
counts = []
for bands in band_options:
    model = LSH(bands)
    for signature in signatures:
        model.add_hash(signature)
    counts.append(len(model.check_candidates()))
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].bar([str(b) for b in band_options], counts, color='#2563eb')
axes[0].set(xlabel='Number of bands', ylabel='Candidate pairs', title='Actual candidate counts')
sim = np.linspace(0, 1, 200)
for bands in band_options:
    axes[1].plot(sim, 1-(1-sim**(100//bands))**bands, label=f'{bands} bands')
axes[1].set(xlabel='Jaccard similarity', ylabel='P(candidate)', title='LSH collision probability')
axes[1].legend(); plt.tight_layout(); plt.show()
LSH: candidates instead of all pairs

Goal: avoid comparing every possible document pair. LSH proposes candidates; a final similarity check can verify them.

LSH banding - Why matching one band is enough

Key idea: A MinHash signature is divided into bands. Two documents become a candidate pair if at least one complete band matches. Changing the band count changes how strict each band is.

# A small illustrative example: 12 hash rows split into 3 bands of 4 rows.
a = np.array([2, 4, 1, 7, 5, 3, 8, 2, 6, 1, 4, 9])
b = np.array([2, 4, 1, 7, 5, 8, 8, 2, 6, 1, 7, 9])
fig, ax = plt.subplots(figsize=(9, 3))
M = np.stack([a, b]).T
ax.imshow(M, cmap='Blues', aspect='auto')
for row in range(12):
    for col in range(2):
        ax.text(col, row, str(M[row, col]), ha='center', va='center', fontsize=9)
for edge in [3.5, 7.5]: ax.axhline(edge, color='black', linewidth=2)
ax.set(xticks=[0,1], xticklabels=['Document A','Document B'], yticks=[1.5,5.5,9.5], yticklabels=['Band 1 (match)','Band 2','Band 3'], title='One identical band → candidate pair')
plt.tight_layout(); plt.show()
total = len(signatures)*(len(signatures)-1)//2
fig, ax = plt.subplots(figsize=(8, 3))
ax.barh(['All possible pairs', 'LSH candidates'], [total, len(candidate_pairs)], color=['#94a3b8','#16a34a'])
ax.set(xlabel='Number of pairs', title='How much does candidate generation narrow the search?')
for j,v in enumerate([total,len(candidate_pairs)]): ax.text(v, j, f' {v:,}', va='center')
plt.tight_layout(); plt.show()
for candidate in list(candidate_pairs)[:5]:
    print("Candidate similar sentence are:")
    print(sentences[candidate[0]])
    print(sentences[candidate[1]])
    print("="*10)
number_of_candidates = 8
for candidate in list(candidate_pairs)[:number_of_candidates]:
    print("Candidate similar documents are:")
    print(sentences[candidate[0]])
    print(sentences[candidate[1]])
    print("="*10)

4. Data Discretization

mu, sigma = 0, 0.1           # mean and standard deviation
s = np.random.normal(mu, sigma, 1000)
n, bins, _ = plt.hist(x = s, bins='auto', color='#0504aa',
                            alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Data Discretization')
plt.text(-0.3, 80, r'$\mu=0, \sigma = 0.1 $')
maxfreq = n.max()
# Set a clean upper y-axis limit.
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
Discretization: continuous values → bins

Trade-off: fewer bins are easier to summarize, but hide detail, more bins reveal detail, but can be noisy.

[Exercise] Visualize the different bins
# TODO
print('Number of bis = ', len(n))
print ('************************************')
print('The number of elements in each bin = ', n)
print ('************************************')
print('The boundaries of the bins = ', bins)
n, bins, _ = plt.hist(df_raisin_n.ConvexArea, bins='auto', color='#0504aa',
                            alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('ConvexArea')
maxfreq = n.max()
# Set a clean upper y-axis limit.
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)