Text analysis: tokenization, statistics, and semantic models
Back to the AI-901 path
AI-901Chapter 3

Microsoft AI-901 Certification Study

Text analysis: tokenization, statistics, and semantic models

Preprocessing, TF-IDF, bag-of-words, Naive Bayes, TextRank, embeddings, cosine similarity, and vector arithmetic

Suggested study time: 36 minutes • Beginner level • Original rewrite based on Microsoft Learn objectives

Neon Microsoft Certified AI-901 Azure AI Fundamentals shield surrounded by generative AI, vision, speech, cloud, and agent symbols

1. Introduction to text analysis

Learning objectives

  • Explain how tokenization and preprocessing prepare a corpus for analysis.
  • Apply frequency, TF-IDF, bag-of-words, Naive Bayes, and TextRank conceptually.
  • Interpret embeddings, cosine similarity, vector arithmetic, and semantic relationships.
  • Connect semantic models with summarization, keywords, entities, classification, and sentiment.

Text analysis is a natural language processing, or NLP, discipline that extracts meaning, structure, and insight from unstructured text. Organizations use it to turn customer feedback, support tickets, contracts, and social media posts into actionable intelligence.

Methods have progressed from statistical term counts to vector language models that can represent meaning. This evolution addresses a core challenge: human language is complex, while computers require numerical representations to analyze it.

Common text-analysis workloads.
TaskOutcome
Language detectionIdentifies one or more languages and often starts a multi-stage pipeline.
Key-term extractionFinds important words and phrases to reveal themes.
Entity detectionLocates people, places, dates, organizations, and other named entities.
PII detectionIdentifies and can redact names, addresses, phone numbers, financial accounts, and other sensitive data.
Text classificationCategorizes documents by content, such as spam versus non-spam.
Sentiment analysisClassifies tone as positive, neutral, or negative.
SummarizationReduces volume while retaining salient points.

Microsoft Learn offers the original material in video and text formats. The written version usually provides additional detail and can supplement the videos.

2. Tokenizing a corpus

The first analysis step is to split a collection of text, called a corpus, into tokens. For simplicity, every distinct word can be treated as a token, although real systems also use subwords, word combinations, and punctuation.

In “We choose to go to the moon,” every occurrence occupies a sequence position. The repeated “to” reuses its vocabulary identifier. This discrete representation makes frequencies easy to count and helps reveal dominant terms.

Simplified token sequence.
PositionToken
1We
2choose
3to
4go
5to
6the
7moon

The best tokenization scheme depends on the problem. A solution may preserve capitalization and punctuation when they convey meaning, or remove them when the goal is simply to compare term frequency.

3. Normalization, stop words, and n-grams

Preprocessing techniques.
TechniqueHow it worksTrade-off
NormalizationMay remove punctuation and convert text to lowercase.Improves simple counts but can erase differences among the surname “Banks,” the noun “banks,” and a period that marks a sentence boundary.
Stop-word removalExcludes functional words such as articles and pronouns that aid readability but carry little thematic meaning.The list must fit the language and domain because a generally common word may still matter in context.
N-gram extractionGroups recurring sequences. One word is a unigram, two form a bigram, and three form a trigram.Phrases such as “artificial intelligence” and “natural language processing” should be treated as units when meaning depends on the combination.

4. Stemming, lemmatization, and part-of-speech tags

Stemming consolidates variants by stripping endings such as “s,” “ing,” and “ed.” The aim is to group terms with a shared root before counting them, even when the resulting stem is not a valid word.

Lemmatization also finds a base form, called a lemma, but applies linguistic rules and vocabulary. It therefore tends to return recognizable words, such as converting “running” to “run,” instead of merely cutting characters.

Part-of-speech, or POS, tagging labels tokens as nouns, verbs, adjectives, adverbs, and other grammatical categories. Linguistic rules and statistical models use both the token and its sentence context to choose the correct tag.

5. Frequency analysis

After tokenization, normalization, and lemmatization, a simple count shows how often each term occurs. The assumption is that recurring terms help identify a document’s themes.

In a passage about AI benefits in business, normalized counts might show “AI” four times, “business” three times, and “benefit,” “customer,” “decision,” and “market” twice each. The pattern points to business value from automation, predictive analytics, productivity, personalization, and market adaptation.

Partial frequency example after preprocessing.
TermFrequency
AI4
business3
benefit2
customer2
decision2
market2
ability1
accuracy1

6. TF-IDF: relevance across documents

Raw frequency works for one document, but terms common throughout a corpus make documents difficult to distinguish. Term frequency-inverse document frequency, or TF-IDF, raises the weight of words that are frequent locally but rare across the collection.

Consider two agent-related samples. One presents declarative creation in Microsoft Copilot Studio through natural language, prompts, templates, intents, actions, data connections, channel publishing, orchestration, governance, and lifecycle management. The other describes code-first development in with SDKs, APIs, conversations, tool calling, state, pipelines, Python, C#, Microsoft AI services, and CI/CD.

“Agent,” “Microsoft,” and “AI” occur often in both samples and identify the broad topic without separating the documents. TF-IDF instead highlights “Copilot,” “Studio,” and “declarative” in the first, and “code,” “develop,” and “Foundry” in the second.

TF(t,d) = number of occurrences of t in document d
IDF(t) = log(N / df(t))
TF-IDF(t,d) = TF(t,d) × log(N / df(t))

N is the document count and df(t) is the number containing the term. A word in both documents when N = 2 has IDF log(2/2) = 0 and no discriminative weight. In the example, “copilot” and “studio” score 2.0794, “declarative” scores 1.3863; “code,” “develop,” and “foundry” score 2.0794 in the other sample.

7. Bag-of-words, Naive Bayes, and classification

Bag-of-words represents a document as a vector of token occurrences or frequencies while ignoring grammar and word order. Machine-learning algorithms can use this vector as input features.

Naive Bayes is a probabilistic classifier based on Bayes’ theorem. In spam filtering, it can learn that phrases such as “miracle cure,” “lose weight fast,” and “anti-aging” occur more often in suspicious health-product messages and use that evidence to estimate a class.

The same setup supports sentiment analysis. Word counts become features, and the model estimates probabilities for labels such as positive or negative.

8. TextRank and extractive summarization

TextRank is an unsupervised graph algorithm. Each sentence can be a node, and edges connect sentences with weights derived from term similarity. Like PageRank, its central idea is that a sentence becomes important when it resembles other important sentences.

  1. Build a graph with sentence nodes and edge weights based on word overlap or cosine similarity between sentence vectors.
  2. Iteratively update each node rank from neighboring scores and weights. The damping factor d is commonly 0.85.
  3. After convergence, select the highest-ranked sentences for the summary.
TextRank(Sᵢ) = (1 − d) + d × Σ[(wⱼᵢ / Σwⱼₖ) × TextRank(Sⱼ)]
TextRank graph with five sentences connected by similarity weights.
Connection thickness represents similarity; central nodes are likely to appear in the extractive summary.

In the cloud-computing example, five sentences cover on-demand resources, servers and storage, Azure as Microsoft’s cloud platform, infrastructure cost reduction, and scalability. The ten pairwise weights are 0.5, 0.6, 0.2, 0.7, 0.2, 0.1, 0.1, 0.5, 0.4, and 0.3. Sentences 1, 3, and 5 may receive the highest scores and form a concise summary.

Selecting existing sentences is extractive summarization. Newer semantic models also support abstractive summarization, which writes new language that condenses source themes. TextRank can work at the word level too: terms become nodes, co-occurrence within a window becomes an edge, and top-ranked nodes become key terms.

9. Semantic language models and embeddings

NLP advances produced deep-learning models that represent tokens as dense multidimensional vectors called embeddings. Word2Vec and GloVe popularized this method: during training, dimension values come to reflect semantic characteristics inferred from usage.

Mathematical vector relationships make many analysis tasks more efficient than purely statistical approaches. Attention extended the method by measuring surrounding-token influence and producing contextual embeddings, which underpin modern models such as the GPT family and generative AI.

Teaching example with three-dimensional vectors.
WordVector
dog[0.8, 0.6, 0.1]
puppy[0.9, 0.7, 0.4]
cat[0.7, 0.5, 0.2]
kitten[0.8, 0.6, 0.5]
young[0.1, 0.1, 0.3]
ball[0.3, 0.9, 0.1]
tree[0.2, 0.1, 0.9]
Word vectors projected into three-dimensional space.
Dog and cat point in nearby directions, as do puppy and kitten, while tree, young, and ball represent different meanings.

10. Cosine similarity and related terms

Cosine similarity compares vector orientation. Values near 1 indicate similar directions, while lower values indicate more distant meanings.

cosine_similarity(A,B) = (A · B) / (||A|| × ||B||)

For dog [0.8, 0.6, 0.1] and cat [0.7, 0.5, 0.2], the dot product is 0.88, magnitudes are about 1.005 and 0.883, and similarity is 0.992. Dog and tree produce 0.333; cat and tree, 0.452. Tree is therefore the semantic odd one out.

Visual comparison of similarity among dog, cat, and tree.
Dog and cat have almost identical orientations, while tree remains distant from both.

11. Vector arithmetic and analogies

Adding or subtracting embeddings can represent linguistic transformations. With the teaching vectors, dog + young yields [0.9, 0.7, 0.4], or puppy; cat + young yields [0.8, 0.6, 0.5], or kitten.

The relationship also works backward: puppy − young returns dog, and kitten − young returns cat. In production, arithmetic rarely yields an exact match; the system searches for the token vector nearest the result.

Vector addition transforming an adult animal into its young counterpart.
The semantic “young” component moves dog and cat vectors toward puppy and kitten.

The same idea solves analogies. To complete “puppy is to dog as kitten is to what?”, calculate kitten − puppy + dog. The result [0.7, 0.5, 0.2] matches cat.

Vector analogy among puppy, dog, kitten, and cat.
Vector operations capture linguistic patterns and enable reasoning over relationships.

12. Text-analysis tasks with semantic models

Using embeddings for text analysis.
TaskSemantic approach
Text summarizationRepresents sentences by averaged or pooled embeddings and extracts the most central; generative models can also produce abstractive summaries.
Keyword extractionCompares word embeddings with the document representation or identifies terms central to all word vectors.
Named entity recognitionFine-tuned models learn clusters for people, organizations, locations, and other types and use context at inference time.
Text classificationAggregates embeddings into document vectors for a classifier or compares them directly with class-prototype vectors.
Sentiment analysisGroups semantically similar documents and separates emotional categories.

13. Exercise and knowledge check

The exercise uses Language Playground to experiment with language tasks and observe how AI analyzes text.

Original screenshot of Language Playground detecting Japanese text.
The real interface capture remains a PNG; only conceptual diagrams were redrawn.

Reworded questions

  1. Does tokenization translate, summarize, or split text into smaller units for analysis?
  2. Which technique measures word importance in one document within a collection: Naive Bayes, TF-IDF, or Word2Vec?
  3. What is the role of embeddings in NLP: duplicating tokens, defining stop words, or representing semantic relationships across dimensions?

Answer key

  • Tokenization divides a corpus into smaller units that can be identified and analyzed.
  • TF-IDF balances local frequency with rarity across the document collection.
  • Embeddings are multidimensional vectors that encode semantic relationships among tokens.

14. Chapter summary

  • Tokenization and preprocessing turn language into analyzable units.
  • Frequency, TF-IDF, bag-of-words, Naive Bayes, and TextRank extract statistical patterns.
  • TextRank produces extractive summaries and keywords from graph centrality.
  • Embeddings represent meaning, and cosine similarity measures semantic proximity.
  • Vector arithmetic expresses linguistic transformations and analogies.
  • Semantic models support summarization, keywords, entities, classification, and sentiment.