.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/09_beyond_unsupervised/plot_03_fccm_document_term.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code or to run this example in your browser via Binder. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_09_beyond_unsupervised_plot_03_fccm_document_term.py: 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: :math:`u_{ik}` of document :math:`k` and :math:`w_{ij}` of term :math:`j` in co-cluster :math:`i`. FCCM (Oh, Honda and Ichihashi) maximizes the *aggregation degree* :math:`\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. .. GENERATED FROM PYTHON SOURCE LINES 22-36 .. code-block:: Python 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}") .. rst-class:: sphx-glr-script-out .. code-block:: none 180 documents, 110 terms, mean count 0.88 .. GENERATED FROM PYTHON SOURCE LINES 37-46 Recovering the blocks --------------------- :math:`\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), :math:`\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 :math:`\lambda_u=0.1` and :math:`\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. .. GENERATED FROM PYTHON SOURCE LINES 46-62 .. code-block:: Python # [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() .. image-sg:: /auto_examples/09_beyond_unsupervised/images/sphx_glr_plot_03_fccm_document_term_001.png :alt: Document--term counts as observed (shuffled), Reordered by the FCCM co-clusters :srcset: /auto_examples/09_beyond_unsupervised/images/sphx_glr_plot_03_fccm_document_term_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none FCCM documents ARI = 1.00, topical terms ARI = 1.00 .. GENERATED FROM PYTHON SOURCE LINES 63-69 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. .. GENERATED FROM PYTHON SOURCE LINES 69-82 .. code-block:: Python 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") .. image-sg:: /auto_examples/09_beyond_unsupervised/images/sphx_glr_plot_03_fccm_document_term_002.png :alt: Scaled term memberships of the four co-clusters :srcset: /auto_examples/09_beyond_unsupervised/images/sphx_glr_plot_03_fccm_document_term_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 83-97 Parameter study: the two regularization weights ----------------------------------------------- Both weights are scanned on a grid. A small :math:`\lambda_u` makes the document memberships nearly crisp; a large :math:`\lambda_u` drives them to :math:`1/c` and dissolves the partition. :math:`\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 :math:`\lambda_u` grows (20--200 for :math:`\lambda_u\le0.1`, only 20 at :math:`\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 :math:`\lambda_w`, since its linear update clips small item memberships to zero instead of keeping every term in play. .. GENERATED FROM PYTHON SOURCE LINES 97-140 .. code-block:: Python # [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") .. rst-class:: sphx-glr-horizontal * .. image-sg:: /auto_examples/09_beyond_unsupervised/images/sphx_glr_plot_03_fccm_document_term_003.png :alt: FCCM: Document ARI, FCCM: Mean largest membership $\max_i u_{ik}$ :srcset: /auto_examples/09_beyond_unsupervised/images/sphx_glr_plot_03_fccm_document_term_003.png :class: sphx-glr-multi-img * .. image-sg:: /auto_examples/09_beyond_unsupervised/images/sphx_glr_plot_03_fccm_document_term_004.png :alt: Fuzzy CoDoK ($T_u=0.3$, $T_w=200$): the 40 terms of largest scaled membership :srcset: /auto_examples/09_beyond_unsupervised/images/sphx_glr_plot_03_fccm_document_term_004.png :class: sphx-glr-multi-img .. rst-class:: sphx-glr-script-out .. code-block:: none 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') .. GENERATED FROM PYTHON SOURCE LINES 141-151 **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 (:math:`\lambda_u` like a typical count, :math:`\lambda_w` like a count summed over a co-cluster's documents), and outside a window of :math:`\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. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.594 seconds) .. _sphx_glr_download_auto_examples_09_beyond_unsupervised_plot_03_fccm_document_term.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/ComplexSystemsIntelligence/fuzzyclust/main?urlpath=lab/tree/notebooks/auto_examples/09_beyond_unsupervised/plot_03_fccm_document_term.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_03_fccm_document_term.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_03_fccm_document_term.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_03_fccm_document_term.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_