drnb notebooks
  • Notebooks
  • GitHub
  1. Articles
  2. Normalized Compression Distance with 20 Newsgroups
  • Experiments in Dimensionality Reduction
  • Articles
    • Do Hubs Hurt?
    • How Does Dimensionality Reduction Transform Distances?
    • Hubness
    • Heavy-tailed UMAP
    • Leopold: Lightweight Estimate of Preservation of Local Density
    • Measuring Media Bias
    • Normalized Compression Distance with 20 Newsgroups
    • PaCMAP: local scaling vs. k-nearest neighbors
    • PaCMAP Repeats
    • Neighbor Overlap and PCA
    • Neighbor Recall: UMAP vs t-SNE
    • Approximating Isomap with k-Nearest Neighbors and Stochastic Metric Multidimensional Scaling
    • Stochastic Metric Multidimensional Scaling
    • Renormalizing after TF-IDF + SVD
    • t-SNE Consistency with Random Initialization
    • UMAP with Annealed Neighbors. 1: Defaults
    • UMAP with Annealed Neighbors. 2: t-UMAP
    • UMAP with Annealed Neighbors. 3: PCA Initialization
    • Spectral Embedding
    • UMATO Evaluation
    • t-SNE Affinity: Gaussian vs. Uniform

On this page

  • Load the Dataset
  • Calculate the Nearest Neighbors
    • Write out the neighbors
  • Read precomputed neighbors
  • Prepare the Nearest Neighbors for UMAP
  • Run UMAP
  • Visualize the Results
  • Comparison with TF-IDF
  • Some k=14 accuracy numbers
    • NCD accuracies
    • TF-IDF accuracies
  1. Articles
  2. Normalized Compression Distance with 20 Newsgroups

UMAP on 20 Newsgroups with Normalized Compression Distance

  • Show All Code
  • Hide All Code

Jiang and co-workers described using the Normalized Compression Distance (NCD) with k-nearest neighbors classification as a light-weight alternative to deep learning for text classification. This got some attention from the ML community and as this is a subject close to my heart so I am glad to see it getting another moment in the sun.

Can NCD be used as a distance measure for use with dimensionality reduction methods? Let’s give it a go using the 20 Newsgroups dataset.

Code
%load_ext lab_black
%load_ext autotime
import numpy as np
import pandas as pd
time: 564 ms (started: 2023-07-17 07:49:59 -07:00)

Load the Dataset

Code
from sklearn.datasets import fetch_20newsgroups

newsgroups = fetch_20newsgroups(subset="all")
time: 1.19 s (started: 2023-07-17 07:49:59 -07:00)

Calculate the Nearest Neighbors

You probably don’t want to do this. I have saved the 150 nearest neighbors in the data folder of this repo so if you just want to do something with the similarities, you should skip to the Read precomputed neighbors below.

The biggest problem with calculating the nearest neighbors of the 20NG dataset is that none of the nearest neighbors methods I am familiar with (Annoy, hnsw, PyNNDescent, FAISS) allow for passing generic distance functions for text data. PyNNDescent comes closest because it allows for custom metric functions, but it validates that the internal data is float-valued. So we will have to do this the slow way: an all-pairs calculation. The slow part is the NCD calculation so I used a ProcessPoolExecutor to split the work up at the cost of a bit of extra memory usage. I also did not use a heap to store the neighbors: as the 20NG dataset contains less than 20,000 observations, it’s not that big a deal to that number of floating point values and sort them.

Code
import gzip
from concurrent.futures import ProcessPoolExecutor
from typing import Any, List, Optional, Tuple

import numpy as np


def calculate_ncd_chunk(args):
    data, x_lens, i, chunk_indices = args
    instance_i = data[i][0]
    ncds = []
    for j in chunk_indices:
        instance_j = data[j][0]
        xy_len = len(gzip.compress(" ".join([instance_i, instance_j]).encode()))
        max_len = max(x_lens[i], x_lens[j])
        min_len = min(x_lens[i], x_lens[j])
        ncd = (xy_len - min_len) / max_len
        ncds.append(ncd)
    return ncds


def ncd_knn(
    data: List[Tuple[str, Any]],
    k: int,
    chunk_size: Optional[int] = None,
    max_workers: Optional[int] = None,
) -> Tuple[np.ndarray, np.ndarray]:
    n = len(data)

    if chunk_size is None:
        if max_workers is None:
            raise ValueError("Please specify max_workers when chunk_size is None")
        chunk_size = int(n / max_workers)
        print(f"Using chunk_size = {chunk_size}")

    distances = np.empty((n, k), dtype=np.float32)
    indices = np.empty((n, k), dtype=int)

    x_lens = np.array([len(gzip.compress(x.encode())) for x, _ in data])

    with ProcessPoolExecutor(max_workers=max_workers) as ex:
        for i in range(n):
            neighbors_heap = np.empty(n, dtype=np.float32)
            chunks = [range(j, min(j + chunk_size, n)) for j in range(0, n, chunk_size)]
            futures = [
                ex.submit(calculate_ncd_chunk, (data, x_lens, i, chunk))
                for chunk in chunks
            ]
            for chunk, future in zip(chunks, futures):
                neighbors_heap[list(chunk)] = future.result()

            sorted_indices = np.argsort(neighbors_heap)
            indices[i] = sorted_indices[:k]
            distances[i] = neighbors_heap[indices[i]]

    return indices, distances
time: 29.9 ms (started: 2023-07-17 07:50:00 -07:00)

Running this on the 20NG data took me around 6 hours so run this next step at your own risk:

Code
# ng20_ncd_knn = ncd_knn(ng20, 150)
time: 743 µs (started: 2023-07-17 07:50:00 -07:00)

Update 29th July 2023: As part of Ken Schutte’s in-depth investigation of the Jiang paper, similar suggestions for speeding up the calculations are made, but in addition some further efficiencies are found for the gzip stage by using the underlying zlib functionality.

Write out the neighbors

This is another step you probably don’t need to do unless you ran the NCD code and want to save the neighbors data somewhere. The drnb_home=Path.cwd().parent / "data" parameter means it will overwrite the pre-saved neighbor data in the data folder, so you will probably want to change the name and/or suffix parameters to save it to a different file.

Code
# from pathlib import Path

# from drnb.io import write_pickle

# ng20_nn_path = write_pickle(
#     ng20_ncd_knn,
#     name="ng20",
#     suffix="ncdnn",
#     drnb_home=Path.cwd().parent / "data",
#     compression="gzip",
# )
time: 2.18 ms (started: 2023-07-17 07:50:00 -07:00)

Read precomputed neighbors

You probably do want to do this. Just read in the neighbor data I already calculated, which is in the data folder of this repo (a sibling folder of the notebooks folder). As long as you don’t want more than the 150-nearest neighbors, this should be fine.

Code
from pathlib import Path

from drnb.io import read_pickle

ng20_ncd_knn = read_pickle(
    name="ng20", suffix="ncdnn", drnb_home=Path.cwd().parent.parent / "data"
)
time: 212 ms (started: 2023-07-17 07:50:00 -07:00)
Code
ng20_ncd_knn
(array([[    0,   333,  1154, ...,  8113, 11464,  9297],
        [    1,  8028,  6468, ..., 15207,  2715,  4847],
        [    2, 12577,  5478, ..., 13622, 10187, 15553],
        ...,
        [18843,  5531, 10762, ..., 10879, 12328, 17746],
        [18844, 11518, 18207, ...,  6020, 17514, 14356],
        [18845, 17662,  1303, ..., 12908, 10337,   666]]),
 array([[0.03220036, 0.6940966 , 0.7101968 , ..., 0.8211091 , 0.8211091 ,
         0.8211091 ],
        [0.02941176, 0.7166948 , 0.733564  , ..., 0.8217993 , 0.8217993 ,
         0.8217993 ],
        [0.0265252 , 0.6120938 , 0.7877984 , ..., 0.9236074 , 0.9236074 ,
         0.9236074 ],
        ...,
        [0.03397028, 0.6602972 , 0.6624204 , ..., 0.7898089 , 0.7898089 ,
         0.7898089 ],
        [0.02796272, 0.54327565, 0.5782857 , ..., 0.84287614, 0.84287614,
         0.84287614],
        [0.02683179, 0.75394845, 0.82146543, ..., 0.872033  , 0.872033  ,
         0.872033  ]], dtype=float32))
time: 7.49 ms (started: 2023-07-17 07:50:01 -07:00)

Note that the distance of an item from itself is not zero, although there is obviously a fairly large gap between the “self” distance and the nearest neighbor, so I am unsure what significance this has.

Prepare the Nearest Neighbors for UMAP

Code
from drnb.embed.umap.umap import umap_knn

ng20_nn = umap_knn(idx=ng20_ncd_knn[0][:, :15], dist=ng20_ncd_knn[1][:, :15])
/home/james/dev/drnb/venv/lib/python3.10/site-packages/umap/distances.py:1063: NumbaDeprecationWarning: The 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details.
  @numba.jit()
/home/james/dev/drnb/venv/lib/python3.10/site-packages/umap/distances.py:1071: NumbaDeprecationWarning: The 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details.
  @numba.jit()
/home/james/dev/drnb/venv/lib/python3.10/site-packages/umap/distances.py:1086: NumbaDeprecationWarning: The 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details.
  @numba.jit()
time: 4.47 s (started: 2023-07-17 07:50:01 -07:00)
/home/james/dev/drnb/venv/lib/python3.10/site-packages/umap/umap_.py:660: NumbaDeprecationWarning: The 'nopython' keyword argument was not supplied to the 'numba.jit' decorator. The implicit default value for this argument is currently False, but it will be changed to True in Numba 0.59.0. See https://numba.readthedocs.io/en/stable/reference/deprecation.html#deprecation-of-object-mode-fall-back-behaviour-when-using-jit for details.
  @numba.jit()

Run UMAP

Code
from umap import UMAP
time: 781 µs (started: 2023-07-17 07:50:05 -07:00)

As we have already got the nearest neighbors, we don’t actually need to pass any other data in. However, UMAP’s validation will be unhappy if no data is provided to fit_transform , if it has a different number of samples to the neighbor data and if any value is NaN, so the most expedient way forward is to pass an n x 1 array of zeros.

Code
coords = UMAP(
    precomputed_knn=ng20_nn, force_approximation_algorithm=True, random_state=42
).fit_transform(np.zeros((len(newsgroups.data), 1), np.float32))
OMP: Info #276: omp_set_nested routine deprecated, please use omp_set_max_active_levels instead.
time: 13.6 s (started: 2023-07-17 07:50:05 -07:00)

Visualize the Results

I am going to use an internal plotting function that makes use of seaborn under the hood. To get the categories showing up properly I must do some slight housekeeping with the target and target names:

Code
from drnb.util import codes_to_categories

description = codes_to_categories(
    newsgroups.target, newsgroups.target_names, col_name="description"
)
description
0                rec.sport.hockey
1        comp.sys.ibm.pc.hardware
2           talk.politics.mideast
3        comp.sys.ibm.pc.hardware
4           comp.sys.mac.hardware
                   ...           
18841                     sci.med
18842             sci.electronics
18843    comp.sys.ibm.pc.hardware
18844               comp.graphics
18845                   rec.autos
Name: description, Length: 18846, dtype: category
Categories (20, object): ['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', ..., 'talk.politics.guns', 'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc']
time: 14.6 ms (started: 2023-07-17 07:50:19 -07:00)

Now we can finally take a look at the results…

Code
from drnb.plot import sns_embed_plot
time: 3.49 s (started: 2023-07-17 07:50:19 -07:00)
Code
sns_embed_plot(
    coords,
    color_col=description,
    cex=4,
    alpha_scale=0.2,
    legend="force",
    figsize=(7, 7),
)

time: 1.94 s (started: 2023-07-17 07:50:22 -07:00)

That looks ok. I can see some actual clusters in there.

Comparison with TF-IDF

As a comparison, let’s look at running UMAP directly on the sparse TF-IDF results. This uses the pre-vectorized results to save some time.

Code
import sklearn.feature_extraction.text
from sklearn.datasets import fetch_20newsgroups_vectorized
time: 1.23 ms (started: 2023-07-17 07:50:24 -07:00)
Code
newsgroups_vectorized = fetch_20newsgroups_vectorized(subset="all")
time: 788 ms (started: 2023-07-17 07:50:24 -07:00)
Code
tfidf = sklearn.feature_extraction.text.TfidfTransformer(norm="l1").fit_transform(
    newsgroups_vectorized.data
)
time: 88.5 ms (started: 2023-07-17 07:50:25 -07:00)

The UMAP docs use metric="hellinger" for this step, but I get a RuntimeWarning: invalid value encountered in sparse_correct_alternative_hellinger so I am going to use boring old cosine instead. The results aren’t hugely different.

Code
tfidf_coords = UMAP(metric="cosine", random_state=42).fit_transform(tfidf)
time: 2min 41s (started: 2023-07-17 07:50:25 -07:00)

The vectorized data is in a different order to the fetch_20newsgroups results, so I need to run codes_to_categories again to get the cluster colors and legend correct:

Code
sns_embed_plot(
    tfidf_coords,
    color_col=codes_to_categories(
        newsgroups_vectorized.target,
        newsgroups_vectorized.target_names,
        col_name="description",
    ),
    cex=4,
    alpha_scale=0.2,
    legend="force",
    figsize=(7, 7),
)

time: 1.65 s (started: 2023-07-17 07:53:07 -07:00)

As much as I was rooting for the NCD approach, I’d say this looks better.

Some k=14 accuracy numbers

To back up my sense that the TF-IDF UMAP results are better than those for NCD, here are some label preservation values, i.e. doing k-nearest neighbor accuracies in the original and embedded spaces. As UMAP uses n_neighbors=15, but each item in a dataset is considered to be its own nearest neighbor, I will use k=14 for classification. Also I will use balanced accuracy where the reported accuracy is the average of averages for each of the 20 classes.

Code
from drnb.eval.labelpres import label_pres
time: 4.55 ms (started: 2023-07-17 08:03:46 -07:00)

NCD accuracies

First, using the NCD distances:

Code
label_pres(
    description.cat.codes.to_numpy(), ng20_ncd_knn[0][:, 1:15], [14], balanced=True
)
array([0.78730837])
time: 29 ms (started: 2023-07-17 08:08:00 -07:00)

So 79% accuracy for the NCD distances. Now to see how well the 2D UMAP coordinates work. We will need to calculate the embedded coordinate nearest neighbors.

Code
from drnb.neighbors import get_exact_neighbors
time: 826 µs (started: 2023-07-17 08:16:40 -07:00)
Code
ncd_umap_neighbors = get_exact_neighbors(name=None, data=coords, n_neighbors=16)
time: 415 ms (started: 2023-07-17 08:17:51 -07:00)

Again, each item in the nearest neighbor list is considered to be its own closest neighbor so we need to account for that.

Code
label_pres(
    description.cat.codes.to_numpy(),
    ncd_umap_neighbors.idx[:, 1:15],
    [14],
    balanced=True,
)
array([0.52760592])
time: 34.3 ms (started: 2023-07-17 08:17:59 -07:00)

53% accuracy. Quite a large drop due to the embedding.

TF-IDF accuracies

I let UMAP handle the neighbor calculation for the TF-IDF results, but under the hood it’s using PyNNDescent, so we can regenerate the nearest neighbors easily enough. Because PyNNDescent is a nearest neighbor descent method reliant on RNG I am not expecting the exact same neighbors, but I have checked that these results give a very similar UMAP output.

Code
from drnb.neighbors.pynndescent import pynndescent_neighbors
time: 1.16 ms (started: 2023-07-17 08:11:02 -07:00)
Code
tfidf_neighbors = pynndescent_neighbors(tfidf, metric="cosine")
time: 2min 2s (started: 2023-07-17 08:11:34 -07:00)
Code
tfidf_neighbors
(array([[    0, 11210, 13994, ..., 18199,  8284, 16880],
        [    1,  1154,  4072, ...,  7596,  5647,  2838],
        [    2,  5266,   702, ..., 13988,  7719, 10314],
        ...,
        [18843, 10518, 11023, ...,  9684,  1066,   654],
        [18844, 18660, 11777, ...,  2011, 11587, 15558],
        [18845, 14094, 17702, ..., 12455, 12782,  2914]], dtype=int32),
 array([[0.00000000e+00, 3.47495055e-01, 4.70872971e-01, ...,
         6.24593463e-01, 6.24889801e-01, 6.29753500e-01],
        [0.00000000e+00, 1.59404722e-01, 4.21334068e-01, ...,
         7.65516014e-01, 7.65750687e-01, 7.71373821e-01],
        [1.19209271e-07, 1.67959434e-01, 2.28724319e-01, ...,
         7.20114172e-01, 7.30006808e-01, 7.31508791e-01],
        ...,
        [0.00000000e+00, 5.67518535e-01, 5.78195945e-01, ...,
         7.44709597e-01, 7.45820269e-01, 7.46301952e-01],
        [0.00000000e+00, 5.63557240e-01, 5.80361807e-01, ...,
         6.24000053e-01, 6.25036070e-01, 6.25102337e-01],
        [0.00000000e+00, 7.57262447e-01, 7.83847445e-01, ...,
         8.33130229e-01, 8.34524307e-01, 8.36388755e-01]]))
time: 4.3 ms (started: 2023-07-17 08:14:46 -07:00)
Code
label_pres(
    codes_to_categories(
        newsgroups_vectorized.target,
        newsgroups_vectorized.target_names,
        col_name="description",
    ).cat.codes.to_numpy(),
    tfidf_neighbors[0][:, 1:15],
    [14],
    balanced=True,
)
array([0.74461993])
time: 26.5 ms (started: 2023-07-17 08:15:17 -07:00)

74% accuracy: so for k=14, the NCD distances actually do a bit better than the cosine distances with TF-IDF. We could look at some other TF-IDF settings but that’s not the point of this notebook.

Code
tfidf_umap_neighbors = get_exact_neighbors(name=None, data=tfidf_coords, n_neighbors=16)
time: 211 ms (started: 2023-07-17 08:18:25 -07:00)
Code
label_pres(
    codes_to_categories(
        newsgroups_vectorized.target,
        newsgroups_vectorized.target_names,
        col_name="description",
    ).cat.codes.to_numpy(),
    tfidf_umap_neighbors.idx[:, 1:15],
    [14],
    balanced=True,
)
array([0.64941256])
time: 39.6 ms (started: 2023-07-17 08:18:38 -07:00)

UMAP on the TF-IDF results has a 65% accuracy with k=14, which is a much smaller drop in accuracy after reducing to 2D. So after applying UMAP, the TF-IDF embeddings are actually about 10% better than with NCD, even though the high-dimensional distances favor NCD.

These calculations back up my perception that the TF-IDF UMAP looks better than the NCD version. But bear in mind it’s easy to get these calculations wrong. That said, there may be some indication here that reproducing the NCD similarities well in 2D with UMAP is harder than the TF-IDF ones.