DTM (Document Term Matrix)

A Document Term Matrix (DTM) is a matrix representation of a text corpus where each row corresponds to a document and each column corresponds to a unique term (word) in the vocabulary - with each cell holding the frequency of that term in that document.

Structure of a DTM

  • Rows - individual documents
  • Columns - unique terms across the entire corpus
  • Cell values - how many times a term appears in a document (or a weighted value like TF-IDF)

Building a DTM in Python

from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd

docs = ["data science is fun", "python for data science"]
vectorizer = CountVectorizer()
matrix = vectorizer.fit_transform(docs)

dtm = pd.DataFrame(matrix.toarray(), columns=vectorizer.get_feature_names_out())
print(dtm)

Why the DTM Matters

The DTM is the standard input format for many text mining and machine learning techniques - it converts a collection of documents into a numeric table that algorithms like clustering, classification, and topic modeling can work with directly.

DTMs are usually very sparse (mostly zeros), since most documents only use a small fraction of the total vocabulary - sparse matrix formats are used in practice to save memory.

What CountVectorizer Does at Each Step

Calling fit_transform() looks like one action, but it hides a small pipeline. Knowing the steps helps you control the result:

  1. Lowercasing turns "Data" and "data" into the same term by default.
  2. Tokenising splits each document into words. The default pattern keeps tokens of two or more letters or digits, so single characters such as "a" disappear.
  3. Building the vocabulary collects every unique token across all documents and gives each one a column number, sorted alphabetically.
  4. Counting fills each row with how often each vocabulary term appears in that document, stored as a sparse matrix.

A worked example by hand

Suppose the corpus has three short reviews: "good phone", "bad phone bad battery" and "good battery". The vocabulary becomes bad, battery, good, phone, and the matrix looks like this:

Documentbadbatterygoodphone
Review 10011
Review 22101
Review 30110

Reading down a column tells you how a word spreads across the corpus. Reading across a row gives a numeric fingerprint of one document, ready for a model.

Weighting Terms with TF-IDF and Tuning the Vocabulary

Raw counts treat every word equally, so common words like "the" can dominate. TF-IDF lowers the weight of terms that appear in many documents and raises the weight of terms that are frequent in one document but rare overall.

from sklearn.feature_extraction.text import TfidfVectorizer

docs = ["good phone", "bad phone bad battery", "good battery"]

vectorizer = TfidfVectorizer(
    stop_words="english",   # drop very common English words
    ngram_range=(1, 2),     # keep single words and two-word phrases
    min_df=1,               # ignore terms in fewer documents than this
    max_df=0.9              # ignore terms in more than 90% of documents
)
dtm = vectorizer.fit_transform(docs)

print(dtm.shape)                          # (documents, terms)
print(vectorizer.get_feature_names_out())

The min_df and max_df settings are your main tools for keeping the vocabulary manageable on large corpora. Two-word phrases help with meaning, as in "not good", but they also make the matrix much wider, so use them deliberately.

A Term Document Matrix (TDM) is simply the transpose of a DTM, with terms as rows. Some text mining tools prefer that layout, but the information is identical.

Common DTM Mistakes and a Practical Checklist

  • Fitting on test data. Fit the vectorizer on training documents only, then call transform() on test documents. Fitting on everything leaks information and makes evaluation look better than it really is.
  • Converting to dense too early. Calling toarray() on a large corpus can exhaust memory. Most scikit-learn models accept the sparse matrix directly.
  • Skipping cleaning. Numbers, HTML fragments and spelling variants all become separate columns unless you clean the text first.
  • Expecting word order or meaning. A DTM is a bag of words. "Dog bites man" and "man bites dog" produce the same row. Word embeddings or transformer models capture context when that matters.

Before you train a model on a DTM, check that you have:

  • decided between raw counts and TF-IDF weights;
  • removed or kept stop words on purpose;
  • limited the vocabulary with document frequency settings;
  • fitted only on training data and reused the same vectorizer for new text.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course