1. What is Tokenization?
Tokenization is the process of breaking text into smaller units called tokens so that a machine-learning model can process the text. Example:2. Why Do We Need Tokenization?
Neural networks work with numbers, not raw text. For example:3. Types of Tokenization
Common approaches include:- Word-level tokenization
- Character-level tokenization
- Subword tokenization
- BPE — Byte Pair Encoding
- WordPiece
4. BPE — Byte Pair Encoding
BPE breaks words into smaller pieces and learns which pieces frequently occur together.Basic idea
Suppose the training data contains:5. Why BPE is Useful
Consider a rare word:Main advantages
- Handles rare words
- Handles new words
- Keeps vocabulary manageable
- Captures meaningful subwords
6. WordPiece
WordPiece is another subword tokenization algorithm. It is famously used with BERT-style models. Example:## means that ing is a continuation of the previous token.
Another example:
7. BPE vs WordPiece
Simple way to remember:
8. BPE Tokenizer Code
We can use Hugging Facetransformers.
Install:
Ġ is how this tokenizer represents a space before a token.
9. Convert BPE Tokens to IDs
10. WordPiece Tokenizer Code
For WordPiece, we can use the BERT tokenizer.11. Convert WordPiece Tokens to IDs
12. Tokenizer encode()
Instead of manually converting tokens to IDs, we can use encode().
13. Better Way: tokenizer()
In modern Hugging Face code, it is common to directly call the tokenizer.
14. What is an Attention Mask?
When sentences have different lengths, padding is often added. Example:15. What are Embeddings?
An embedding is a numerical representation of text. Instead of representing:16. Sentence Embeddings
A sentence embedding represents an entire sentence using a single vector. Example:17. Sentence Transformers
Sentence Transformers is a Python library designed to generate useful embeddings for sentences, paragraphs, and other text. Install it:18. Generate Sentence Embeddings
19. View the Embedding
20. Sentence Similarity
One major application of sentence embeddings is semantic similarity. For example:21. Cosine Similarity Code
Install scikit-learn if necessary:22. Compare Two Sentences Directly
You can also compare only two sentences.23. Complete Example
This combines tokenization + sentence embeddings.24. Tokenization vs Embeddings
These two concepts are related but different.Tokenization
Converts text into smaller pieces.Sentence Embedding
Converts the meaning of the entire sentence into a vector.25. Complete NLP Pipeline
The overall process can be remembered as:26. Practical Applications
1. Semantic Search
Search by meaning rather than exact keywords.2. Duplicate Detection
3. Recommendation Systems
Find similar:- Products
- Articles
- Questions
- Documents