Sub topic 1
Why Models Need Text as Numbers
A machine-learning model works with numerical values. It can add, multiply, compare, and optimize numbers, but it cannot directly use a sentence such as “the service was fast.” Text must first become a numeric representation called a feature vector. A feature is a measurable input, and a vector is an ordered list of numbers.
For text classification, each number can represent whether a word appears, how often it appears, or how informative it is. The model then learns relationships between these numbers and the target label. For example, a spam classifier might learn that messages containing “winner” and “claim” often have the spam label.
Prerequisites
This chapter assumes that you know basic Python, NumPy arrays, and the general fit and predict pattern of machine-learning classifiers. You should also be comfortable with vectors and simple tabular data.
From documents to vectors
Suppose the training collection contains these documents:
| Document | Text |
|---|---|
| D1 | “cats chase mice” |
| D2 | “dogs chase balls” |
| D3 | “cats sleep” |
A simple representation uses the vocabulary, which is the ordered set of terms selected from the collection:
[balls, cats, chase, dogs, mice, sleep]
Each document becomes a vector with one position for each vocabulary term:
- D1:
[0, 1, 1, 0, 1, 0] - D2:
[1, 0, 1, 1, 0, 0] - D3:
[0, 1, 0, 0, 0, 1]
The value is one when the term occurs and zero otherwise. A count-based representation instead stores the number of occurrences. This approach is called a bag of words because it records which terms occur while ignoring their original order.
Why a shared vocabulary matters
Every document must use the same vector positions. If “cats” means position two for one document but position five for another, the model cannot compare them. The resulting rows form a document-term matrix: documents are rows, vocabulary terms are columns, and cell values are features.
A new document is transformed using the vocabulary learned during training. Unknown terms usually contribute no value in a fixed vocabulary. This keeps the input shape stable, which is required by most estimators.
Choosing the representation
Binary presence is useful when repetition should not matter. Raw counts preserve repetition, which can help when repeated terms carry emphasis. TF-IDF weighting reduces the influence of terms appearing in many documents and increases the influence of distinctive terms. The next chapters develop these choices and their formulas.
Exercise
Exercise
Why must every document use the same vocabulary order when converted to vectors?
Show answer
Each vector position represents one specific feature. A shared order ensures that the model compares the same term across documents.