NLP Task and text representation: From word frequency to context

From the TF-IDF case for two short documents, a distinction is made between task labels, verbs, serial expressions and pre-training targets.

System Chapter . StepCollate in 2 Graphics6 self-measurement3 First-hand sources
Start Body
Learning objectives and first steps4 objectives • 3 first fixes

Try to do it after reading

  • Define text input and labels by task
  • Handheld TF-IDF with cosine search
  • Distinguishing static vectors from context
  • Identification of token borders, interdiction and evaluation of leakage

Suggested first

  • Conditional probability
  • Vector Factor
  • Embedding and Classified Loss

The same paragraph, which corresponds to different oversight tasks

For a product description, it can predict the type of document, extract an entity, search the relevant provisions, or generate a summary. These tasks use similar text input, but require different output structures and labels. Classifications are usually one tab per piece, with a sequence of one tab per token, and a question-and-answer forecast location interval, which produces a series of outputs. The task and monitoring unit should be clearly defined before the model is selected, thus avoiding a uniform “text-reading capacity” to mask the assessment of differences.

This document uses only two short English documents and a glossary of words, avoiding the choice of Chinese words to be hidden in the calculation. Source core for 2026-10-29: CS224N Page As Winter 2026, scikit-learn Text feature document is 1.9.1, BERT Using the original thesis. The code is only standard Python and no real language model is loaded.

The word is input protocol, not irrelevant cleaning

Characters, words and subwords define different units. The word boundary in Chinese is not usually a visible space; The English word, case, punctuation and number may also change the vocabulary. Subwords ease the unincorporated word problem, but the number of token is different from the number of characters and cannot replace the frame length with the character length. Both the wordbox version, the special token and the regularized rules should be recorded with the model.

Assuming the input token is indexed as[B,T]After Embedding[B,T,D]I don't know. The labels of the sequence should also be aligned with the subwords: when a word is separated into multiple pieces, it must be clear whether to monitor the first film, copy the label or use other alignment rules. Padding is in place, not natural text; The valid location of mask and loss is independently checked.

The same text corresponds to different output unitsA short text outputs a single tab to the document group, labels the output to the sequence to the token tab, and exports the new token sequence to the generated task.TextDocument classification: a categorySequence label: one label for each tokenGenerate: a new token sequenceOversight unit decides to export shape, loss denominator and evaluation method
The three branches in the figure represent three separate tasks, not a system that must be implemented in a sequential manner.

The word bag first provides an explanatory baseline

Set the vocabulary to[loan,risk,rate]I don't know. Document d1 asloan risk, d2 forloan rate, the original word frequency vectors are [11,01] and [10,1], respectively. The word bags do not keep the order, but they clearly indicate the contribution of a word to the match. Faced with short-text classification or precise terminology retrieval, it was still a worthy contrast to be retained, rather than being meaningless when large models appeared.

Use smooth IDF:idf(t)=log((1+N)/(1+df(t)))+1, of which N is the number of training documents, and df is the number of documents containing the word. This example N = 2, loan appears on both pages, idf = 1; risk and rate appear each time, idf =1+log(3/2)≈1.405465I don't know. Here, tf uses original numbers, does not enable sublinear_tf, and ends with L2 being regularized and cannot be confused with other IDF-defined numbers.

idf(t)=log(1+N1+df(t))+1

d1 weighted with [1,405465,0] and with a reclassification of approximately [0.579737, 0.8148002,0]; d2 is [0.579739, 0,0814802]. Only risk is consulted and converted to [0,10] IDF to be re-synthesized as [0,01], with a cosine from d1 of 0.8148002 and d2 of zero. The high matches are derived from the overlap of the term in the specific list of terms, and not from the fact that the entire financial semantics have been extrapolated by the system.

Aligning Word weights for two documentsloan has a weight of about 0.58 in both documents, risk in the first book of about 81, rate in the second book of about 81.loanriskrated1: Solidd2: Dotted LineThe word weight length is drawn on the same scale
Single L2 for each vector is regularized and the length scale displays the contributions of keywords and common words.
# 标准 Python,已执行;词表与平滑IDF全部显式指定。
import math
vocab = ['loan','risk','rate']
docs = [['loan','risk'],['loan','rate']]
idf = [math.log((1+len(docs))/(1+sum(t in d for d in docs)))+1 for t in vocab]
def encode(tokens):
raw = [tokens.count(t)*weight for t,weight in zip(vocab,idf)]
length = math.sqrt(sum(v*v for v in raw))
return [v/length for v in raw] if length else raw
first, second, query = encode(docs[0]), encode(docs[1]), encode(['risk'])
score = lambda a,b: sum(x*y for x,y in zip(a,b))
assert abs(score(first,query)-.8148024746671689)<1e-12
assert score(second,query)==0

From static vector to context

The static Embedding indexes the same word in the same vector and it is difficult to distinguish directly its meaning in different contexts. The RNN and Transformer encoders use the sequence context to change their current position. BERT learns in pre-training using two-way context, etc., and then hands on the head according to task; It is not a calibration probability that can be directly compared after inputting any text.

Two-way visibility and self-return visibility cannot be mixed. Document categories allow you to read the full input text and not to read future targets when generating the next token. Even if both used Transformer, the training samples, mask, tag relocation and loss were different. The model is selected by asking which context to use, rather than by comparing parameters only.

The most easily missing boundary in text trials

The vocabulary and IDF should be displayed on the training document fit, confirming only transform; Adding all the tests to the statistics will change the protocol. Close duplication of documents, the same template or the same author ' s rewrite cross-assembly is also exaggerated. Generating tasks should also record hint templates, decoding configurations and output cutbacks, without strictly comparing results under different reasoning budgets with conditions.

Long document cut-offs may throw away the target evidence and segmentation may undermine the entity ' s cross-sectional relationship. Sequence labels check token with character offsets, and the extraction results should be able to map back to the original text. Chinese full-angle characters, Unicode regularization and desensitization may also change the position, and shape cannot only be checked on model lengths while ignoring the alignment of the original text.

Indicators should be tasked: classification should be based on categories and thresholds, entities often match the full span, looking at the range and ranking of candidates, and generating a distinction between surface overlap and factual correctness. An overall score is not a substitute for the analysis of the failure sample. The retention of simple baselines and fixed small examples is often easier to judge what the new model addresses.

Retain retrospective text maps before and after the model

A full text sample should preferably be traced back to the original document, regularized text, token sequence, valid location and target. The debug is performed by checking manually a short example of a label, number and unincorporated word before checking a long text cut. If the output is the original span, the return results need to use the original deviation instead of using the token index as a character index without checking.

The search should also distinguish between exact matching of words and semantic recall. Models, dates, amounts and negative terms often require accuracy, and semantic vectors may still represent the opposite conclusion. (b) The thinning and denseness of the candidate group can be combined and then processed by the proper reassignment and validation of the task; Whether improvements are to be compared with the same candidate budget under a fixed query set cannot be demonstrated by just one or two successful statements.

Self-measurement and interpretation

loan Why is idf exactly 1?

It appears in all two training documents with a smooth ratio (1+2)/(1+2)=1, log 0 plus 1.

Repeat risk twice. Is the same unidirectional vector as before?

Usually different, the original tf is increased and then consolidated; A second value or logarithmic tf is another definition.

Why can't the phrases distinguish between "A like B" and "B like A"?

(b) The same words may be counted in exactly the same number and the order and role are lost; Use n-gram or sequence to indicate that the relevant information is being introduced.

The number of physical labels after sub-wording differs from the number of token. Can you train directly?

Clear alignment rules and neglects are needed and labels cannot be left silent.

BERT can read left and right, so can the task be generated and the answer to the future read?

No, you can't. Visible scope is determined by the mission agreement, and future targets must be hidden when the next token is projected.

The test set is used to estimate idf without labels, and there is no leak at all?

The general summary assessment still does not allow test distributions to participate in training transformations; Unless other agreements are expressly adopted and disclosed.

Next is " How the weight of Attention becomes a new expression " , read Data Severage and Leaks. The above three single-source counterpart missions, TF-IDF engagement and context pre-training; The standard Python value of this chapter has been implemented and no operation has been carried out for the terminologist, scikit-learn or BERT framework experiment.

Sources and reconciliations

Definitions, methods and interfaces are available.

  1. Stanford CS224N — Natural Language Processing with Deep Learning
  2. scikit-learn — Text feature extraction
  3. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding

Figures and calculations are reorganized according to this chapter. Mathematical measurements, framework operations and real business effects are described separately in the body of the text.

← Back to the knowledge directory
Ask Max Ask about this site
Ask Max ↗

Opening the assistant…

Paper figure

Photo comments

LEAVE A NOTE

About this photograph

Connecting to the discussion board…

    Comments become public after moderation. You can delete your own comments from this browser.
    No email is required. Clearing cookies prevents this browser from claiming earlier comments.

    MAX WANG / INDEX

    Find something

    Enter a keyword, or explore the directory below.