Fuzzy co-clustering of a document–term matrix#

A document–term matrix has two kinds of entities, documents (rows) and terms (columns), and a topic is a pair: a group of documents and the vocabulary that characterizes it. Fuzzy co-clustering assigns memberships to both: \(u_{ik}\) of document \(k\) and \(w_{ij}\) of term \(j\) in co-cluster \(i\). FCCM (Oh, Honda and Ichihashi) maximizes the aggregation degree \(\sum_{ikj}u_{ik}w_{ij}r_{kj}\) regularized by the entropies of both membership sets; Fuzzy CoDoK (Kummamuru, Dhawale and Krishnapuram) uses quadratic regularizers instead. Neither needs a distance between sparse count vectors. The data are a synthetic corpus: four topics with vocabularies of different size, Poisson counts that are high inside a topic block and low elsewhere, plus twenty general terms that occur everywhere at the background rate. Rows and columns are shuffled, so the blocks are invisible until the co-clusters reorder the matrix.

import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import adjusted_rand_score

from fuzzyclust.coclustering import FCCM, FCoDoK, make_block_matrix, plot_coclusters, plot_item_memberships
from fuzzyclust.plotting import PALETTE

R, doc_topic, term_topic = make_block_matrix(
    n_blocks=4, n_objects_per_block=(30, 40, 50, 60), n_items_per_block=(15, 20, 25, 30),
    in_rate=3.0, out_rate=0.3, n_noise_items=20, random_state=0,
)
topical = term_topic >= 0
print(f"{R.shape[0]} documents, {R.shape[1]} terms, mean count {R.mean():.2f}")
180 documents, 110 terms, mean count 0.88

Recovering the blocks#

\(\lambda_u\) is measured in the units of a document’s aggregation (a weighted mean of its counts over the co-cluster’s terms, about 3 inside a block), \(\lambda_w\) in those of a term’s aggregation (a weighted sum over the documents, which grows with the size of the co-cluster). With \(\lambda_u=0.1\) and \(\lambda_w=20\) FCCM recovers the four topics exactly, both for the documents and for the topical terms, and the reordered matrix shows the four diagonal blocks.

# [snippet:fit]
fccm = FCCM(n_clusters=4, lambda_u=0.1, lambda_w=20.0, n_init=5, random_state=0).fit(R)
print(f"FCCM documents ARI = {adjusted_rand_score(doc_topic, fccm.labels_):.2f}, "
      f"topical terms ARI = {adjusted_rand_score(term_topic[topical], fccm.item_labels_[topical]):.2f}")
# [/snippet:fit]

fig, axes = plt.subplots(1, 2, figsize=(11, 4.4))
axes[0].imshow(R, cmap="Greys", aspect="auto", interpolation="nearest")
axes[0].set_title("Document--term counts as observed (shuffled)")
axes[0].set_xlabel("terms")
axes[0].set_ylabel("documents")
plot_coclusters(R, fccm, ax=axes[1], cbar=False)
axes[1].set_title("Reordered by the FCCM co-clusters")
plt.tight_layout()
Document--term counts as observed (shuffled), Reordered by the FCCM co-clusters
FCCM documents ARI = 1.00, topical terms ARI = 1.00

The term memberships show which vocabulary characterizes a topic. Each co-cluster distributes one unit of membership over the terms, so the raw values are small for a large vocabulary; scaled by their maximum they show that every topic owns its block of terms, ranked by how often the terms occur in the topic’s documents, while the twenty general terms (right of the dotted line) have a membership near zero in all co-clusters.

fig, ax = plt.subplots(figsize=(11, 3.2))
W = fccm.item_membership_ / fccm.item_membership_.max(axis=0, keepdims=True)
order = np.lexsort((-W.max(axis=1), np.where(topical, fccm.item_labels_, 99)))
for i in range(4):
    ax.plot(np.arange(order.size), W[order, i], color=PALETTE[i], lw=1.4, label=f"co-cluster {i + 1}")
ax.axvline(topical.sum() - 0.5, color="0.4", ls=":", lw=1)
ax.text(topical.sum() + 1, 0.9, "general terms", fontsize=8, color="0.3")
ax.set_xlabel("terms (topical terms ordered by co-cluster, then the general terms)")
ax.set_ylabel(r"$w_{ij}/\max_j w_{ij}$")
ax.set_title("Scaled term memberships of the four co-clusters")
ax.legend(frameon=False, fontsize=8, ncol=4)
ax.grid(True, color="0.9")
Scaled term memberships of the four co-clusters

Parameter study: the two regularization weights#

Both weights are scanned on a grid. A small \(\lambda_u\) makes the document memberships nearly crisp; a large \(\lambda_u\) drives them to \(1/c\) and dissolves the partition. \(\lambda_w\) has a usable window: if it is too small, a co-cluster concentrates its whole item membership on a few frequent terms; if it is too large, the term memberships become uniform. The window closes from above as \(\lambda_u\) grows (20–200 for \(\lambda_u\le0.1\), only 20 at \(\lambda_u=1\)), because both weights soften the partition and their effects add up. Fuzzy CoDoK on the same grid (printed) is less sensitive to \(\lambda_w\), since its linear update clips small item memberships to zero instead of keeping every term in play.

# [snippet:scan]
lambdas_u = (0.03, 0.1, 0.3, 1.0, 3.0)
lambdas_w = (1.0, 5.0, 20.0, 50.0, 200.0)
grid = np.zeros((len(lambdas_u), len(lambdas_w)))
fuzziness = np.zeros_like(grid)
for a, lu in enumerate(lambdas_u):
    for b, lw in enumerate(lambdas_w):
        model = FCCM(n_clusters=4, lambda_u=lu, lambda_w=lw, n_init=5, random_state=0).fit(R)
        grid[a, b] = adjusted_rand_score(doc_topic, model.labels_)
        fuzziness[a, b] = model.membership_.max(axis=1).mean()
# [/snippet:scan]

fig, axes = plt.subplots(1, 2, figsize=(11, 4.0))
for ax, Z, title, cmap in ((axes[0], grid, "Document ARI", "viridis"),
                           (axes[1], fuzziness, r"Mean largest membership $\max_i u_{ik}$", "magma")):
    im = ax.imshow(Z, cmap=cmap, vmin=0, vmax=1, origin="lower")
    ax.set_xticks(range(len(lambdas_w)))
    ax.set_xticklabels([f"{v:g}" for v in lambdas_w])
    ax.set_yticks(range(len(lambdas_u)))
    ax.set_yticklabels([f"{v:g}" for v in lambdas_u])
    ax.set_xlabel(r"$\lambda_w$ (term entropy weight)")
    ax.set_ylabel(r"$\lambda_u$ (document entropy weight)")
    ax.set_title(f"FCCM: {title}")
    for a in range(Z.shape[0]):
        for b in range(Z.shape[1]):
            ax.text(b, a, f"{Z[a, b]:.2f}", ha="center", va="center", fontsize=7,
                    color="white" if Z[a, b] < 0.6 else "black")
    plt.colorbar(im, ax=ax, fraction=0.045, pad=0.03)
plt.tight_layout()

for lu in (0.1, 0.3, 1.0):
    row = []
    for lw in (20.0, 50.0, 200.0, 1000.0):
        codok = FCoDoK(n_clusters=4, lambda_u=lu, lambda_w=lw, n_init=5, random_state=0).fit(R)
        row.append(f"{adjusted_rand_score(doc_topic, codok.labels_):.2f}")
    print(f"Fuzzy CoDoK, T_u = {lu:g}: ARI for T_w = 20, 50, 200, 1000 -> " + ", ".join(row))

fig, ax = plt.subplots(figsize=(11, 3.0))
codok = FCoDoK(n_clusters=4, lambda_u=0.3, lambda_w=200.0, n_init=5, random_state=0).fit(R)
plot_item_memberships(codok, ax=ax, top=40)
ax.set_title("Fuzzy CoDoK ($T_u=0.3$, $T_w=200$): the 40 terms of largest scaled membership")
  • FCCM: Document ARI, FCCM: Mean largest membership $\max_i u_{ik}$
  • Fuzzy CoDoK ($T_u=0.3$, $T_w=200$): the 40 terms of largest scaled membership
Fuzzy CoDoK, T_u = 0.1: ARI for T_w = 20, 50, 200, 1000 -> 1.00, 1.00, 1.00, 1.00
Fuzzy CoDoK, T_u = 0.3: ARI for T_w = 20, 50, 200, 1000 -> 1.00, 1.00, 1.00, 1.00
Fuzzy CoDoK, T_u = 1: ARI for T_w = 20, 50, 200, 1000 -> 0.78, 0.77, 0.82, 0.83

Text(0.5, 1.0, 'Fuzzy CoDoK ($T_u=0.3$, $T_w=200$): the 40 terms of largest scaled membership')

Take-away. Co-clustering answers two questions at once: which documents form a topic, and which terms make it a topic. FCCM recovers the shuffled blocks of the corpus exactly and gives the general terms a membership near zero everywhere. Its two entropy weights have to be set in the units of the aggregations they regularize (\(\lambda_u\) like a typical count, \(\lambda_w\) like a count summed over a co-cluster’s documents), and outside a window of \(\lambda_w\) the solution degenerates. Fuzzy CoDoK, with quadratic regularizers and linear updates, works on the same data with a wider window of the term weight.

Total running time of the script: (0 minutes 0.594 seconds)

Gallery generated by Sphinx-Gallery