Analysis of the speedups provided by similarity search module

In this notebook, we will explore the gains in time and memory of the different methods we use in the similarity search module.

[1]:
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

from aeon.similarity_search.subsequence import MASS, NaiveSubsequenceSearch
from aeon.utils.numba.general import sliding_mean_std_one_series

ggplot_styles = {
    "axes.edgecolor": "white",
    "axes.facecolor": "EBEBEB",
    "axes.grid": True,
    "axes.grid.which": "both",
    "axes.spines.left": False,
    "axes.spines.right": False,
    "axes.spines.top": False,
    "axes.spines.bottom": False,
    "grid.color": "white",
    "grid.linewidth": "1.2",
    "xtick.color": "555555",
    "xtick.major.bottom": True,
    "xtick.minor.bottom": False,
    "ytick.color": "555555",
    "ytick.major.left": True,
    "ytick.minor.left": False,
}

plt.rcParams.update(ggplot_styles)

Computing means and standard deviations for all subsequences

When we want to compute a normalised distance, given a time series X of size m and a query q of size l, we have to compute the mean and standard deviation for all subsequences of size l in X. One could do this task by doing the following:

[2]:
def rolling_window_stride_trick(X, window):
    """
    Use strides to generate rolling/sliding windows for a numpy array.

    Parameters
    ----------
    X : numpy.ndarray
        numpy array
    window : int
        Size of the rolling window

    Returns
    -------
    output : numpy.ndarray
        This will be a new view of the original input array.
    """
    a = np.asarray(X)
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)


def get_means_stds(X, query_length):
    """Compute the means and standard deviations of rolling windows in a time series."""
    windows = rolling_window_stride_trick(X, query_length)
    return windows.mean(axis=-1), windows.std(axis=-1)


rng = np.random.default_rng(12)
size = 100
query_length = 10

# Create a random series with 1 feature and 'size' timesteps
X = rng.random((1, size))
means, stds = get_means_stds(X, query_length)
print(means.shape)
(1, 91)

One issue with this code is that it actually recompute a lot of information between the computation of mean and std of each windows. Suppose that the window we compute the mean for W_i = {x_i, ..., x_{i+(l-1)}, to do this, we sum all the elements and divide them by l. You then want to compute the mean for W_{i+1} = {x_{i+1}, ..., x_{i+1+(l-1)}, which shares most of its values with W_i expect for x_i and x_{i+1+(l-1).

The optimization here consists in keeping a rolling sum, we only compute the full sum of the l values for the first window W_0, then to obtain the sum for W_1, we remove x_0 and add x_{1+(l-1)} from the sum of W_0. We can also a rolling squared sum to compute the standard deviation.

The sliding_mean_std_one_series function implement the computation of the means and standard deviations using these two rolling sums. The last argument indicates the dilation to apply to the subsequence, which is not used here, hence the value of 1 in the code below.

[3]:
sizes = [500, 1000, 5000, 10000, 25000, 50000]
query_lengths = [50, 100, 250, 500]
times = pd.DataFrame(
    index=pd.MultiIndex(levels=[[], []], codes=[[], []], names=["size", "query_length"])
)
# A first run for numba compilations if needed
sliding_mean_std_one_series(rng.random((1, 50)), 10, 1)
for size in sizes:
    for query_length in query_lengths:
        X = rng.random((1, size))
        _times = %timeit -r 3 -n 3 -q -o get_means_stds(X, query_length)
        times.loc[(size, query_length), "full computation"] = _times.average
        _times = %timeit -r 3 -n 3 -q -o sliding_mean_std_one_series(X, query_length, 1)
        times.loc[(size, query_length), "sliding_computation"] = _times.average
[4]:
fig, ax = plt.subplots(ncols=len(query_lengths), figsize=(20, 5), dpi=200, sharey=True)
for j, (i, grp) in enumerate(times.groupby("query_length")):
    grp.droplevel(1).plot(label=i, ax=ax[j])
    ax[j].set_title(f"query length {i}")
    ax[j].set_yscale("log")
ax[0].set_ylabel("time in seconds")
plt.show()
../_build/doctrees/nbsphinx/examples_similarity_search_code_speed_8_0.png

As you can see, the larger the size of q, the greater the speedups. This is because the larger the size of q, the more recomputation we avoid by using a sliding sum.

Computing the Euclidean distance with a dot product obtained from convolution

The standard way to compute the (squared) euclidean distance between a query Q = {q_1, ..., q_l} and a candidate subsequence W_i = {x_i, ..., x_{i+(l-1)} is to compute it as \(d(Q,W_i) = \sum_j^l (x_{i+j} - q_j)^2\).

We can also express this distance as \(d(Q,W_i) = Q^2 + W_i^2 - 2Q.W_i\), in our case, we can use the fact a cross correlation can be used to compute \(Q*X\) to obtain the dot products between \(Q\) and all \(W_i\). The timing difference become even more important for large input, when it becomes worth to use a fast Fourrier transform to compute the convolution in the frequency domain. See scipy.signal.convolve documentation for more information.

[5]:
sizes = [500, 1000, 5000, 10000, 20000, 30000, 50000]
query_lengths = [0.01, 0.05, 0.1, 0.2]
times = pd.DataFrame(
    index=pd.MultiIndex(levels=[[], []], codes=[[], []], names=["size", "query_length"])
)

for size in sizes:
    for _query_length in query_lengths:
        query_length = int(_query_length * size)
        X = rng.random((1, size))
        q = rng.random((1, query_length))
        mask = np.ones((1, size - query_length + 1), dtype=bool)
        # Used for numba compilation before timings
        mass = MASS(length=query_length).fit(X)
        mass.compute_distance_profile(q)
        dummy = NaiveSubsequenceSearch(length=query_length).fit(X)
        dummy.compute_distance_profile(q)

        _times = %timeit -r 3 -n 3 -q -o dummy.compute_distance_profile(q)
        times.loc[(size, _query_length), "Naive Euclidean distance"] = _times.average

        _times = %timeit -r 3 -n 3 -q -o mass.compute_distance_profile(q)
        times.loc[(size, _query_length), "Euclidean distance with MASS"] = (
            _times.average
        )
[6]:
fig, ax = plt.subplots(ncols=len(query_lengths), figsize=(20, 5), dpi=200)
for j, (i, grp) in enumerate(times.groupby("query_length")):
    grp.droplevel(1).plot(label=i, ax=ax[j])
    ax[j].set_title(f"query length {i}")
    ax[j].set_yscale("log")
ax[0].set_ylabel("time in seconds")

plt.show()
../_build/doctrees/nbsphinx/examples_similarity_search_code_speed_13_0.png

The same reasoning holds for the normalised (squared) euclidean distance, we can use the normalize parameter of the two estimators to set this option. In the normalised case, the formula used to computed the normalised (squared) euclidean distance is taken from the paper Matrix Profile I: All Pairs Similarity Joins for Time Series, see MASS algorithm.

[7]:
sizes = [500, 1000, 5000, 10000, 20000, 30000, 50000]
query_lengths = [0.01, 0.05, 0.1, 0.2]
times = pd.DataFrame(
    index=pd.MultiIndex(levels=[[], []], codes=[[], []], names=["size", "query_length"])
)

for size in sizes:
    for _query_length in query_lengths:
        query_length = int(_query_length * size)
        X = rng.random((1, size))
        q = rng.random((1, query_length))
        mask = np.ones((1, size - query_length + 1), dtype=bool)
        # Used for numba compilation before timings
        mass = MASS(length=query_length, normalize=True).fit(X)
        mass.compute_distance_profile(q)
        dummy = NaiveSubsequenceSearch(length=query_length, normalize=True).fit(X)
        dummy.compute_distance_profile(q)

        _times = %timeit -r 3 -n 3 -q -o dummy.compute_distance_profile(q)
        times.loc[(size, _query_length), "Naive Normalised Euclidean distance"] = (
            _times.average
        )

        _times = %timeit -r 3 -n 3 -q -o mass.compute_distance_profile(q)
        times.loc[(size, _query_length), "Normalised Euclidean distance with MASS"] = (
            _times.average
        )
[8]:
fig, ax = plt.subplots(ncols=len(query_lengths), figsize=(20, 5), dpi=200)
for j, (i, grp) in enumerate(times.groupby("query_length")):
    grp.droplevel(1).plot(label=i, ax=ax[j])
    ax[j].set_title(f"query length {i}")
    ax[j].set_yscale("log")
ax[0].set_ylabel("time in seconds")
plt.show()
../_build/doctrees/nbsphinx/examples_similarity_search_code_speed_16_0.png

Tuning and precision of the approximate whole-series index (SimHashIndexANN)

The methods above speed up exact subsequence search. The whole_series.SimHashIndexANN index instead trades a little accuracy for speed on large collections, exposing two knobs – n_tables and n_bits_per_table – plus a choice of floating-point precision. The cells below measure, on one large pool of real series, how those choices affect recall, class purity, and query speed. See the overview notebook for how the index works.

Accuracy vs query speed: n_tables (L) and n_bits_per_table (k)

To see how the index behaves on a realistically large collection, we build one by concatenating three unrelated real UCR datasets – ECG5000 (ECG), Wafer (semiconductor sensor) and FordA (automotive sensor) – into a single pool of ~17000 series. They have different native lengths, and SimHash needs equal-length series, so each is zero-padded to a common length (the longest series) first. A random subset is held out as queries.

The three panels show how the two knobs affect three metrics. The x-axis is n_bits_per_table (k) and each line is a value of n_tables (L):

  • n_tables (L, the lines) – more tables give a candidate more chances to collide with the query, making its collision count a finer signal: higher lines have higher recall, at the cost of larger candidate sets and slower queries.

  • n_bits_per_table (k, x-axis) – more bits make buckets more selective, which shrinks candidate sets and speeds queries up sharply. On this data recall is barely affected at first (true neighbors are close enough to keep colliding) and only declines gently once buckets get very selective.

Because there is no exact rerank, this is a genuinely approximate index: ranking by collision count alone gives modest recall (left panel; about 0.25-0.6 here, versus 1.0 for the exact search). The middle panel reports class purity@k – the fraction of the k returned neighbors that share the query’s class label (labels are made globally unique per dataset, since the three datasets reuse values like 1/-1). Unlike recall, this is a label-based, semantic quality measure, and it is capped not at 1 but at the exact NN’s own purity (dashed line) – even exact Euclidean neighbors are not all the same class. n_tables is the main lever for recall and purity; n_bits_per_table is the main lever for speed. The dashed line in the speed panel is brute force – every config here stays faster than brute force, but with too few bits the candidate set is so large that gathering it eats up most of that advantage, while at larger k the index is several times faster. So the index is worthwhile when approximate neighbors are acceptable and query speed on large collections matters. (A rerank option to trade speed back for exact recall is a planned future addition. Timings are machine-dependent.)

[9]:
import time
import warnings

from aeon.datasets import load_classification
from aeon.similarity_search.whole_series import NaiveSeriesSearch, SimHashIndexANN

# Build ONE large, real collection by concatenating several unrelated UCR datasets.
# SimHash needs equal-length series, so each dataset is zero-padded to a common
# length (the longest series) before stacking. The panels below are measured on
# this pool, so we can read off how BOTH knobs -- n_tables (L) and n_bits_per_table
# (k) -- affect recall, class purity, and query speed.
k = 5  # number of neighbors to retrieve
dataset_names = ["ECG5000", "Wafer", "FordA"]
normalize = True  # use raw series; set True to z-normalize before hashing/distance
n_jobs = 1


def pad_to(X, length):
    """Right zero-pad (or truncate) every univariate series in X to `length`."""
    out = np.zeros((X.shape[0], 1, length))
    m = min(X.shape[-1], length)
    out[:, 0, :m] = X[:, 0, :m]
    return out


# Zero-pad each dataset to the longest native length so no samples are distorted
# (unlike resampling, which would stretch/compress the time axis). The datasets are
# supervised, so we also keep their class labels -- prefixed with the dataset name
# so they are globally unique (the three datasets reuse values like "1"/"-1").
loaded = [load_classification(name) for name in dataset_names]
target_length = max(X.shape[-1] for X, _ in loaded)
pool = np.concatenate([pad_to(X, target_length) for X, _ in loaded])
labels = np.concatenate(
    [
        np.array([f"{name}:{label}" for label in y])
        for name, (_, y) in zip(dataset_names, loaded)
    ]
)

# Randomly split the pool into held-out queries and the indexed collection. We
# permute pool and labels together (so they stay aligned) then slice, which makes
# the queries span all datasets instead of one end of the concatenation.
n_query = 500
rng = np.random.default_rng(0)
perm = rng.permutation(len(pool))
pool, labels = pool[perm], labels[perm]
queries, db = pool[:n_query], pool[n_query:]
query_labels, db_labels = labels[:n_query], labels[n_query:]
n = db.shape[0]
print(f"pool: {n} real series of length {target_length} from {dataset_names}")

n_bits_grid = [4, 8, 16, 32]
n_tables_grid = [10, 20, 40, 80]

# Exact references: the true k-NN (for recall) and their class purity -- the ceiling
# the approximate index can reach, since even exact NN is not 100% same-class.
exact = NaiveSeriesSearch(normalize=normalize, n_jobs=n_jobs).fit(db)
exact_preds = [exact.predict(qi, k=k)[0] for qi in queries]
exact_neighbours = [set(p) for p in exact_preds]
exact_purity = np.mean(
    [np.sum(db_labels[p] == ql) / k for p, ql in zip(exact_preds, query_labels)]
)


def mean_predict_ms(estimator):
    """Return the mean predict time per query, in milliseconds."""
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        estimator.predict(queries[0], k=k)  # warmup, excludes numba compilation
        t0 = time.perf_counter()
        for query in queries:
            estimator.predict(query, k=k)
    return (time.perf_counter() - t0) / len(queries) * 1e3


# Sweep both knobs: one curve per n_tables, across n_bits_per_table.
recall_grid, purity_grid, time_grid = {}, {}, {}
for n_tables in n_tables_grid:
    recalls, purities, times = [], [], []
    for n_bits in n_bits_grid:
        index = SimHashIndexANN(
            n_tables=n_tables,
            n_bits_per_table=n_bits,
            random_state=0,
            normalize=normalize,
            n_jobs=n_jobs,
        ).fit(db)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            preds = [index.predict(qi, k=k)[0] for qi in queries]
        recalls.append(
            np.mean([len(set(p) & e) / k for p, e in zip(preds, exact_neighbours)])
        )
        purities.append(
            np.mean(
                [np.sum(db_labels[p] == ql) / k for p, ql in zip(preds, query_labels)]
            )
        )
        times.append(mean_predict_ms(index))
    recall_grid[n_tables] = recalls
    purity_grid[n_tables] = purities
    time_grid[n_tables] = times
    print(
        f"n_tables={n_tables:3d}: "
        f"recall={[f'{r:.2f}' for r in recalls]}  "
        f"purity={[f'{p:.2f}' for p in purities]}  "
        f"ms={[f'{t:.3f}' for t in times]}"
    )

brute_force_ms = mean_predict_ms(exact)
print(f"brute force: {brute_force_ms:.3f} ms/query (N={n})")
pool: 16585 real series of length 500 from ['ECG5000', 'Wafer', 'FordA']
n_tables= 10: recall=['0.20', '0.28', '0.31', '0.31']  purity=['0.81', '0.82', '0.77', '0.67']  ms=['0.482', '0.212', '0.138', '0.153']
n_tables= 20: recall=['0.30', '0.36', '0.40', '0.37']  purity=['0.83', '0.83', '0.81', '0.68']  ms=['0.622', '0.301', '0.167', '0.174']
n_tables= 40: recall=['0.42', '0.46', '0.47', '0.44']  purity=['0.86', '0.84', '0.82', '0.69']  ms=['0.839', '0.383', '0.218', '0.308']
n_tables= 80: recall=['0.52', '0.54', '0.54', '0.49']  purity=['0.86', '0.85', '0.82', '0.69']  ms=['1.304', '0.555', '0.372', '0.382']
brute force: 31.909 ms/query (N=16585)
[10]:
fig, (ax_recall, ax_purity, ax_time) = plt.subplots(1, 3, figsize=(18, 4))

# Panel 1: recall vs exact NN -- one line per n_tables, x-axis n_bits_per_table
for n_tables in n_tables_grid:
    ax_recall.plot(
        n_bits_grid, recall_grid[n_tables], marker="o", label=f"n_tables={n_tables}"
    )
ax_recall.axhline(1.0, color="gray", linestyle="--", linewidth=1, label="exact")
ax_recall.set_xlabel("n_bits_per_table")
ax_recall.set_ylabel(f"mean recall@{k}")
ax_recall.set_ylim(0, 1.05)
ax_recall.set_title("Recall vs exact NN")
ax_recall.legend()
ax_recall.grid(True, alpha=0.3)

# Panel 2: class purity -- fraction of returned neighbors sharing the query's class
for n_tables in n_tables_grid:
    ax_purity.plot(
        n_bits_grid, purity_grid[n_tables], marker="o", label=f"n_tables={n_tables}"
    )
ax_purity.axhline(
    exact_purity, color="gray", linestyle="--", linewidth=1, label="exact NN"
)
ax_purity.set_xlabel("n_bits_per_table")
ax_purity.set_ylabel(f"mean same-class@{k}")
ax_purity.set_ylim(0, 1.05)
ax_purity.set_title("Class purity")
ax_purity.legend()
ax_purity.grid(True, alpha=0.3)

# Panel 3: query time (log) -- same lines, brute force as reference
for n_tables in n_tables_grid:
    ax_time.plot(
        n_bits_grid, time_grid[n_tables], marker="o", label=f"n_tables={n_tables}"
    )
ax_time.axhline(
    brute_force_ms, color="gray", linestyle="--", linewidth=1, label="brute force"
)
ax_time.set_yscale("log")
ax_time.set_xlabel("n_bits_per_table")
ax_time.set_ylabel("predict time (ms / query)")
ax_time.set_title(f"Query speed (N={n})")
ax_time.legend()
ax_time.grid(True, alpha=0.3, which="both")

plt.tight_layout()
plt.show()
../_build/doctrees/nbsphinx/examples_similarity_search_code_speed_20_0.png

Hashing precision: float32 vs float64

SimHash keeps only the sign of each random projection, so the magnitude of the dot products – and hence their precision – is thrown away. SimHashIndexANN therefore hashes in whatever floating dtype you pass it (float64 by default), and passing float32 input runs the projection step in single precision: faster, half the memory, and – because a sign almost never flips between float32 and float64 – it returns essentially the same neighbors.

The gain on the whole fit is modest (the projection is only part of the cost; building the hash tables dominates on large collections), but it is free and nearly lossless, so converting to float32 is worth doing whenever you hold a large collection in memory. The cell below fits the same ~17000-series pool in both precisions and checks that the returned neighbors agree. Rather than timing fit by hand, it reads each fit’s duration from the built-in fit_time_millis_ attribute that every similarity search estimator sets after fit.

[11]:
# The index hashes in the dtype of the data you pass it (float64 by default).
# Because only the SIGN of each projection is kept, float32 returns the same
# neighbors while making the projection step faster and halving memory. Every
# similarity search estimator records its fit time in `fit_time_millis_`, so we
# read that instead of timing fit by hand.
db64 = db.astype(np.float64)
db32 = db.astype(np.float32)


def best_fit_ms(data, rep=3):
    """Fit `rep` times; return the fastest fit_time_millis_ and a fitted index."""
    best = None
    for _ in range(rep):
        index = SimHashIndexANN(random_state=0, normalize=False, n_jobs=1).fit(data)
        if best is None or index.fit_time_millis_ < best:
            best = index.fit_time_millis_
    return best, index


ms64, idx64 = best_fit_ms(db64)
ms32, idx32 = best_fit_ms(db32)

# Do both precisions return the same neighbors? (mean overlap over queries)
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    overlap = np.mean(
        [
            len(set(idx64.predict(q, k=k)[0]) & set(idx32.predict(q, k=k)[0])) / k
            for q in queries
        ]
    )

print(f"fit float64: {ms64:4d} ms   data {db64.nbytes / 1e6:5.1f} MB")
print(f"fit float32: {ms32:4d} ms   data {db32.nbytes / 1e6:5.1f} MB")
print(
    f"float32 fit speedup: {ms64 / ms32:.2f}x   "
    f"mean neighbor overlap (f32 vs f64): {overlap:.3f}"
)
fit float64:  199 ms   data  66.3 MB
fit float32:  140 ms   data  33.2 MB
float32 fit speedup: 1.42x   mean neighbor overlap (f32 vs f64): 1.000
[ ]:


Generated using nbsphinx. The Jupyter notebook can be found here.

binder