Runoob Tutorial ArchiveEnglish

Advanced NLP Techniques

Advanced NLP Techniques

We actually interact with NLP every day: the suggested words when typing on a mobile phone keyboard, the spam filtered automatically by email applications, foreign websites you understand with translation software—these are all applications of Natural Language Processing (NLP).

Before ChatGPT appeared, NLP had been developing for decades, but the technical threshold was very high. You needed to understand a long series of concepts such as word segmentation, part-of-speech tagging, syntactic parsing, and semantic role labeling, and you still had to manually design features to make the machine "understand" some language.

Today, large language models have made all of this simple. However, understanding the technical trajectory of NLP allows you to more deeply grasp why large models can achieve these things and where their limitations lie.

This module will take you from word embeddings all the way to today's large language models, building a complete NLP knowledge system.

87edab9 9365 483 996 c7871ace4d78

Learning Path: Word Embeddings → Pre-trained Models → Three Major Paradigms (BERT/GPT/T5) → Downstream Tasks (Classification, NER, Translation, Summarization). Each step has corresponding code examples to help you apply the theory.


Evolution History of Pre-trained Language Models

The development of NLP can be clearly divided into several stages, each with a characteristic technological breakthrough.

Word2Vec: The Revolution of Word Embeddings

Before 2013, the way computers processed text was very primitive.

Typically, "One-Hot Encoding" is used: each word corresponds to a very long vector where only one position is 1 and the rest are 0. For example, if the vocabulary has 100,000 words, each word is a 100,000-dimensional vector.

The problem with this method is obvious: the vectors contain no semantic information; the distance between "cat" and "dog" is the same as the distance between "cat" and "table."

The core idea of Word2Vec is: the meaning of a word is defined by the words around it.

Example

============================================

Word2Vec Basic Concept Demonstration

Training a Simple Word Embedding Model using the gensim Library

============================================

First, install gensim: pip install gensim

from

gensim.

models

import

Word2Vec

import

numpy

as

np

Prepare training data: some simple sentences

sentences

=

[

   

[

"I"

,

"like"

,

"to eat"

,

"Apple"

]

,

   

[

"I"

,

"like"

,

"eat"

,

"banana"

]

,

   

[

"Cat"

,

"likes"

,

"to eat"

,

"fish"

]

,

   

[

"dog"

,

"like"

,

"Eat"

,

"Meat"

]

,

   

[

"Apple"

,

"is"

,

"a kind of"

,

"fruit"

]

,

   

[

"Banana"

,

"is"

,

"a"

,

"Fruit"

]

,

   

[

"Cat"

,

"is"

,

"A type of"

,

"animal"

]

,

   

[

"dog"

,

"is"

,

"a"

,

"animal"

]

,

   

[

"RUNOOB"

,

"is"

,

"a"

,

"Programming"

,

"Website"

]

,

   

[

"Learning"

,

"Programming"

,

"Go"

,

"RUNOOB"

]

,

]

Train Word2Vec model

vector_size: Dimension of word vectors

window: Context window size (look at several words before and after)

min_count: Ignore words with frequency less than this value

workers: Number of threads for parallel training

model

=

Word2Vec

(

sentences

=

sentences

,

vector_size

=

50

,

 

Each word is represented by a 50-dimensional vector

    window

=

3

,

     

Look at the 3 words before and after

min_count

=

1

,

   

Keep all words

workers

=

4

,

epochs

=

100

     

Train for 100 rounds

)

Get word vectors

apple_vector

=

model.

wv

[

"apple"

]

print

(

f

"'apple's word vector (first 10 dimensions): {apple_vector[:10]}"

)

print

(

f

"Word vector dimension: {len(apple_vector)}"

)

Calculate the similarity between words

similarity

=

model.

wv

.

similarity

(

"Apple"

,

"Banana"

)

print

(

f

"'apple' and 'banana' similarity: {similarity:.4f}"

)

similarity

=

model.

wv

.

similarity

(

"Apple"

,

"cat"

)

print

(

f

"'apple' and 'cat' similarity: {similarity:.4f}"

)

Find the most similar word

print

(

"Words most similar to 'cat':"

)

for

word

,

score

in

model.

wv

.

most_similar

(

"cat"

,

topn

=

3

)

:

   

print

(

f

"{word}: {score:.4f}"

)

print

(

"\nWords most similar to 'RUNOOB':"

)

for

word

,

score

in

model.

wv

.

most_similar

(

"RUNOOB"

,

topn

=

3

)

:

   

print

(

f

" {word}: {score:.4f}"

)

Classic word vector operation: King - Man + Woman ≈ Queen

Try it in our small corpus: Fruit - Apple + Fish ≈ ?

if

"apple"

in

model.

wv

and

"fish"

in

model.

wv

and

"fruit"

in

model.

wv

:

result

=

model.

wv

.

most_similar

(

positive

=

[

"Fruit"

,

"Fish"

]

,

negative

=

[

"Apple"

]

,

topn

=

3

)

   

print

(

"\n'fruit' - 'apple' + 'fish' ≈"

)

   

for

word

,

score

in

result:

       

print

(

f

"{word}: {score:.4f}"

)

Word2Vec proved one thing: semantics can be represented in a vector space.

But it has a limitation: each word has only one fixed vector, regardless of the context. For example, "bank" has different meanings in "river bank" and "bank account," but Word2Vec gives the same vector.

ELMo: Contextual Word Embeddings

ELMo (Embeddings from Language Models), which appeared in 2018, solved this problem.

The idea behind ELMo is: instead of giving each word a fixed vector beforehand, it looks at the entire sentence to generate a vector for that word.

Even the word "bank" will have one vector in "I went to the bank" and another in "the river bank."

ELMo uses bidirectional LSTM (Long Short-Term Memory) to model context, marking the first large-scale use of the "pre-training + fine-tuning" paradigm.

GPT-1: Unidirectional pre-training

In 2018, OpenAI also released GPT-1 (Generative Pre-training Transformer).

Its characteristics are:

  1. Uses a Transformer decoder instead of LSTM

  2. Unidirectional: only looks at preceding words to predict the next word

  3. Generative: can continue writing text

GPT-1 demonstrated the immense potential of Transformers in NLP tasks.

BERT: Bidirectional Pre-training

In late 2018, Google released BERT (Bidirectional Encoder Representations from Transformers), which revolutionized the NLP field.

The core innovations of BERT are:

  1. Bidirectional: looking at context both before and after

  2. MLM (Masked Language Model): randomly masking some words and having the model predict them

  3. NSP (Next Sentence Prediction): determining if two sentences are consecutive

BERT achieved the best results on 11 NLP tasks at the time, marking the entry of NLP into the "pre-trained model era."

The leap from GPT-3 to ChatGPT

In 2020, GPT-3 was released with 175 billion parameters.

People discovered that when models are large enough and data is abundant enough, an "Emergence" phenomenon occurs—the model suddenly gains capabilities that smaller models do not have, such as few-shot learning and complex reasoning.

At the end of 2022, ChatGPT was released, making the model's output more aligned with human preferences through RLHF (Reinforcement Learning from Human Feedback), truly bringing AI to the masses.

Let's summarize this evolutionary history in a table:

Year Model Core Idea Historical Significance
2013 Word2Vec The meaning of a word is defined by the words around it The word embedding revolution, vector representation of semantics
2018 ELMo Context-aware word vectors First implementation of a vector representation for polysemy
2018 GPT-1 Transformer decoder, unidirectional pre-training Proving the potential of Transformer
2018 BERT Transformer encoder, bidirectional pre-training NLP enters the era of pre-trained models
2020 GPT-3 175 billion parameters, emergent abilities Showcasing the infinite possibilities of large models
2022 ChatGPT RLHF + conversational ability AI truly reaches the masses

In-depth analysis of BERT

BERT is a milestone in the history of NLP and is worth our deep understanding.

MLM (Masked Language Modeling) task

BERT's core pre-training task is MLM: randomly replacing 15% of the words in a sentence with [MASK] and having the model predict the original word.

For example, the sentence "I like to eat apples" might become "I [MASK] to eat apples," and the model needs to predict that [MASK] is "like."

Why do this? Because this forces the model to utilize information from both the preceding and succeeding context, rather than just looking at the left or the right.

In actual operation, these 15% of words are not all replaced with [MASK], but rather:

  1. 80% of the time replaced with [MASK]

  2. 10% of the time, replace it with a random word

  3. 10% of the time, keep the original word unchanged

This is done to make the model more robust—it cannot be certain whether a word has been replaced and must truly understand the context.

NSP (Next Sentence Prediction) task

BERT's second pre-training task is NSP: given two sentences A and B, determine if B is the actual next sentence after A.

Positive example: A="I like to eat apples", B="Apples are a fruit"

Negative example: A="I like to eat apples", B="The weather is really nice today"

This task helps the model understand the relationship between sentences and is very helpful for tasks such as question answering and natural language inference.

BERT's applicable scenarios

BERT is an "encoder" architecture, good at understanding language, suitable for:

text classification, sentiment analysis, named entity recognition, question answering, natural language inference, etc.

It is not very good at text generation, which is GPT's strength.

Standard process for fine-tuning BERT

Let's use the Hugging Face Transformers library to practically fine-tune BERT for text classification:

Example

============================================

Fine-tune BERT using Hugging Face for text classification

Task: Determine if the sentence has positive or negative sentiment

============================================

First, install dependencies:

pip install transformers datasets torch scikit-learn

import

torch

from

transformers

import

(

BertTokenizer

,

BertForSequenceClassification

,

TrainingArguments

,

Trainer

,

)

from

datasets

import

Dataset

,

load_metric

import

numpy

as

np

from

sklearn.

model_selection

import

train_test_split

============================================

1. Prepare data

============================================

Construct a simple sentiment classification dataset

texts

=

[

   

"This product is really easy to use, I love it."

,

   

"The quality is too poor, very disappointed."

,

   

"The RUNOOB tutorial is very clear, and it's easy to learn."

,

   

"The logistics were very slow, and the packaging was damaged."

,

   

"The photo quality of this phone is great."

,

   

"Poor service attitude, won't come again"

,

   

"The book's content is very exciting, recommended to buy"

,

   

"The movie was boring, I fell asleep watching it"

,

   

"The food at this restaurant is delicious"

,

   

"The game has too many bugs, the experience is very poor"

,

   

"RUNOOB's NLP tutorial was very helpful"

,

   

"The interface design of this software is very good"

,

   

"The delivery person was very friendly"

,

   

"The clothing size is inaccurate, and the color is wrong"

,

   

"The hotel environment is very quiet, and I slept very well"

,

   

Customer service response is slow, the issue is not resolved

,

]

labels

=

[

   

1

,

0

,

1

,

0

,

1

,

0

,

1

,

0

,

1

,

0

,

1

,

1

,

1

,

0

,

1

,

0

]

 

1=positive, 0=negative

Split training set and validation set

train_texts

,

val_texts

,

train_labels

,

val_labels

=

train_test_split

(

    texts

,

labels

,

test_size

=

0.25

,

random_state

=

42

)

Create Dataset object

train_dataset

=

Dataset.

from_dict

(

{

"text"

: train_texts

,

"label"

: train_labels

}

)

val_dataset

=

Dataset.

from_dict

(

{

"text"

: val_texts

,

"label"

: val_labels

}

)

============================================

2. Load tokenizer and model

============================================

Use Chinese BERT model

model_name

=

"bert-base-chinese"

tokenizer

=

BertTokenizer.

from_pretrained

(

model_name

)

model

=

BertForSequenceClassification.

from_pretrained

(

    model_name

,

num_labels

=

2

 

Binary classification task

)

============================================

3. Data preprocessing: Convert text into model input

============================================

def

tokenize_function

(

examples

)

:

   

return

tokenizer

(

examples

[

"text"

]

,

padding

=

"max_length"

,

truncation

=

True

,

max_length

=

64

   

)

Apply preprocessing

tokenized_train

=

train_dataset.

map

(

tokenize_function

,

batched

=

True

)

tokenized_val

=

val_dataset.

map

(

tokenize_function

,

batched

=

True

)

============================================

4. Define evaluation metrics

============================================

metric

=

load_metric

(

"accuracy"

)

def

compute_metrics

(

eval_pred

)

:

logits

,

labels

=

eval_pred

predictions

=

np.

argmax

(

logits

,

axis

=

1

)

   

return

metric.

compute

(

predictions

=

predictions

,

references

=

labels

)

============================================

5. Configure training arguments

============================================

training_args

=

TrainingArguments

(

output_dir

=

"./runoob-bert-sentiment"

,

 

Output directory

    num_train_epochs

=

3

,

                   

Number of training rounds

per_device_train_batch_size

=

4

,

       

Training batch size

per_device_eval_batch_size

=

4

,

         

Evaluation batch size

warmup_steps

=

5

,

                       

Warm-up steps

weight_decay

=

0.01

,

                   

Weight decay

logging_dir

=

"./logs"

,

                 

Log directory

logging_steps

=

10

,

evaluation_strategy

=

"epoch"

,

         

Evaluate once per epoch

save_strategy

=

"epoch"

,

learning_rate

=

2e-5

,

    load_best_model_at_end

=

True

,

)

============================================

6. Create Trainer and start training

============================================

trainer

=

Trainer

(

    model

=

model

,

    args

=

training_args

,

    train_dataset

=

tokenized_train

,

    eval_dataset

=

tokenized_val

,

    compute_metrics

=

compute_metrics

,

)

Start training (commented out because it takes a long time and requires a GPU)

print("Starting training...")

trainer.train()

============================================

7. Using a trained model for prediction

============================================

Here we directly use the original model to demonstrate the prediction process

In actual use, you should use the model saved after training with trainer

def

predict_sentiment

(

text

,

model

,

tokenizer

)

:

   

"""Predict sentence sentiment"""

inputs

=

tokenizer

(

text

,

return_tensors

=

"pt"

,

padding

=

True

,

truncation

=

True

,

max_length

=

64

   

)

model.

eval

(

)

   

with

torch.

no_grad

(

)

:

outputs

=

model

(

**inputs

)

logits

=

outputs.

logits

probabilities

=

torch.

softmax

(

logits

,

dim

=

1

)

prediction

=

torch.

argmax

(

probabilities

,

dim

=

1

)

.

item

(

)

    label_map

=

{

0

:

"Negative"

,

1

:

"Positive"

}

confidence

=

probabilities

[

0

]

[

prediction

]

.

item

(

)

   

return

{

       

"text"

: text

,

       

"sentiment"

: label_map

[

prediction

]

,

       

"confidence"

: confidence

,

       

"negative_prob"

: probabilities

[

0

]

[

0

]

.

item

(

)

,

       

"positive_prob"

: probabilities

[

0

]

[

1

]

.

item

(

)

,

   

}

Test a few sentences

test_texts

=

[

   

"The RUNOOB tutorial is really great!"

,

   

"The quality of this product is too poor"

,

   

"The weather is really nice today"

,

   

"I don't really like this movie"

,

]

print

(

"Test model prediction (using pre-trained bert-base-chinese):"

)

print

(

"-"

50

)

for

text

in

test_texts:

   

Note: This uses the original model directly without fine-tuning; the results are for demonstration purposes only.

result

=

predict_sentiment

(

text

,

model

,

tokenizer

)

   

print

(

f

"Text: {result['text']}"

)

   

print

(

f

"Sentiment: {result['sentiment']}"

)

   

print

(

f

"Confidence: {result['confidence']:.4f}"

)

   

print

(

f

"Positive probability: {result['positive_prob']:.4f}"

)

   

print

(

f

"Negative probability: {result['negative_prob']:.4f}"

)

   

print

(

"-"

50

)

Note: The code above demonstrates the complete workflow, but fine-tuning BERT in practice requires a GPU and a long time. In a production environment, you can also consider using a lighter model (such as distilbert) or directly using the API of a large model.


In-depth analysis of the GPT series

GPT (Generative Pre-trained Transformer) took a different path from BERT.

Autoregressive language model

GPT is "autoregressive": it generates word by word, using all previously generated words to predict the next word at each step.

For example, to generate "I like eating apples", the process is:

  1. Input "I", predict the next word as "like"

  2. Input "I like", predict the next word as "eating"

  3. Input "I like eating", predict the next word as "apples"

This method is naturally suited for text generation.

Decoder-Only architecture

GPT only uses the Transformer decoder, while BERT only uses the encoder.

A characteristic of the decoder is "Masked Self-Attention"—each position can only see the positions to its left, not the positions to its right.

This is reasonable because text generation proceeds from left to right; you cannot peek at words that have not yet been generated.

Discovery of Scaling Law

The most important discovery of the GPT series is the Scaling Law: model performance has a power-law relationship with model size, data volume, and computational resources.

Simply put: the larger the model, the more data, and the longer the training, the better the results, and this improvement is predictable without obvious plateaus.

This is why the GPT series has continuously been "scaling up": GPT-1 (117 million) $\rightarrow$ GPT-2 (1.5 billion) $\rightarrow$ GPT-3 (175 billion).


T5 and the Seq2Seq Paradigm

There is also a third paradigm: the Encoder-Decoder structure, with T5 being a representative example.

Unified Text-to-Text Framework

The core idea of T5 (Text-to-Text Transfer Transformer) is to unify all NLP tasks into a "text-to-text" format.

For example:

Text classification: Input "Classify: This movie is very good" -> Output "Positive"

Translation: Input "Translate English to French: Hello world" -> Output "Bonjour le monde"

Summarization: Input "Summarize: This is an article about..." -> Output "This article mainly talks about..."

The advantage of this unified framework is that the same model can perform various tasks without needing to change the model structure for each task.

Encoder-decoder working mechanism

The encoder is responsible for understanding the input text, and the decoder is responsible for generating the output text.

Taking translation as an example:

  1. The encoder reads "Hello world" and generates an "understood" representation.

  2. The decoder generates "Bonjour le monde" word by word based on this representation.

The decoder can "attend" to different positions of the encoder—for example, when generating "Bonjour", it pays more attention to "Hello", and when generating "monde", it pays more attention to "world".


Comparison of the three paradigms: BERT vs GPT vs T5

Let's compare these three architectures in a table:

Feature BERT GPT T5
Architecture Encoder-only Decoder-only Encoder-Decoder
Attention Bidirectional (look at context before and after) Unidirectional (only look at preceding context) Encoder is bidirectional, decoder is unidirectional
Pre-training task MLM (Masked Language Modeling) Autoregressive language modeling Span Corruption
Strengths Understanding models: Classification, NER, Question Answering Generation models: Continuation, Dialogue Transformation models: Translation, Summarization, Rewriting
Representative models BERT, RoBERTa, ALBERT GPT-1/2/3/4, ChatGPT T5, BART, mT5
Typical applications Sentiment analysis, spam filtering Writing assistant, conversational robot Machine translation, document summarization

Most large models today adopt a Decoder-only architecture (GPT route) because it performs best in generation and can be continuously improved through Scaling Law. However, other two architectures still have advantages in specific tasks.


Text classification

Text classification is one of the most common NLP tasks and is the best entry task for beginners.

Practical multi-class classification

Multi-class classification is assigning a label to a text, where there are multiple options for the label.

For example: news classification (technology, sports, entertainment, finance), customer service ticket classification, product review classification, etc.

Example

============================================

Text Classification Practice: Comparison of Multiple Solutions

============================================

from

typing

import

List

,

Dict

,

Any

============================================

Approach 1: Traditional Machine Learning + TF-IDF

Suitable for small datasets, strong interpretability

============================================

def

traditional_text_classification_demo

(

)

:

   

"""Use traditional methods for text classification"""

   

from

sklearn.

feature_extraction

.

text

import

TfidfVectorizer

   

from

sklearn.

naive_bayes

import

MultinomialNB

   

from

sklearn.

pipeline

import

Pipeline

   

Training data

texts

=

[

       

"I bought a stock today, and it went up a lot."

,

       

"Dollar-cost averaging is a good wealth management method."

,

       

"The forward of this team scored a goal"

,

       

"The NBA playoffs are amazing"

,

       

"The camera on this phone takes great pictures"

,

       

"RUNOOB's programming tutorial is very clear"

,

       

"The plot of this movie is very touching"

,

       

"The songs on that album are very good to listen to"

,

   

]

labels

=

[

"Finance"

,

"Finance"

,

"Sports"

,

"Sports"

,

"Technology"

,

"Technology"

,

"Entertainment"

,

"Entertainment"

]

   

Create pipeline: TF-IDF + Naive Bayes

pipeline

=

Pipeline

(

[

       

(

"tfidf"

,

TfidfVectorizer

(

)

)

,

 

Convert text into TF-IDF features

       

(

"classifier"

,

MultinomialNB

(

)

)

,

 

Naive Bayes classifier

   

]

)

   

Training

pipeline.

fit

(

texts

,

labels

)

   

Test

test_texts

=

[

       

"The stock dropped, and I'm in a bad mood"

,

       

"Game-winning shot in the last second of a basketball game"

,

       

"The new laptop has strong performance"

,

       

"RUNOOB's new NLP tutorial"

,

   

]

predictions

=

pipeline.

predict

(

test_texts

)

probabilities

=

pipeline.

predict_proba

(

test_texts

)

   

print

(

"Scheme one: Traditional machine learning + TF-IDF"

)

   

print

(

"-"

50

)

   

for

text

,

pred

,

probs

in

zip

(

test_texts

,

predictions

,

probabilities

)

:

       

print

(

f

"Text: {text}"

)

       

print

(

f

"Prediction: {pred}"

)

       

print

(

f

"All probabilities: {dict(zip(pipeline.classes_, probs))}"

)

       

print

(

)

============================================

Approach Two: Using Hugging Face pipeline

Suitable for rapid prototyping, no training required

============================================

def

huggingface_pipeline_demo

(

)

:

   

"""Use Hugging Face's pre-trained pipeline"""

   

print

(

"Option Two: Hugging Face Pipeline"

)

   

print

(

"-"

50

)

   

try

:

       

from

transformers

import

pipeline

       

Use the sentiment analysis pipeline (English)

classifier

=

pipeline

(

"sentiment-analysis"

)

test_texts

=

[

           

"I love RUNOOB tutorials!"

,

           

"This movie is terrible."

,

       

]

results

=

classifier

(

test_texts

)

       

for

text

,

result

in

zip

(

test_texts

,

results

)

:

           

print

(

f

"Text: {text}"

)

           

print

(

f

"Sentiment: {result['label']}"

)

           

print

(

f

"Confidence: {result['score']:.4f}"

)

           

print

(

)

   

except

Exception

as

e:

       

print

(

f

"You need to install transformers first: pip install transformers"

)

       

print

(

f

"Error: {e}"

)

============================================

Solution Three: Using Large Model API (Recommended)

Suitable for production environment, best effect

============================================

def

llm_based_classification_demo

(

)

:

   

"""Text classification demo using LLM (simulation)"""

   

print

(

"Plan Three: Large Model Classification (Demonstration Idea)"

)

   

print

(

"-"

50

)

   

When actually using it, call APIs like OpenAI/Anthropic

   

This demonstrates the prompt design for classification

   

def

classify_with_llm

(

text:

str

,

categories: List

[

str

]

)

Dict

[

str

,

Any

]

:

       

"""Simulated function for classification using LLM"""

       

Real scenario: Calling LLM API

       

prompt = f"""Please classify the following text and return only the category name.

       

text: {text}

       

Optional categories: {', '.join(categories)}"""

       

Perform a simple keyword matching here to simulate

category_map

=

{

           

"Finance"

:

[

"Stocks"

,

"Funds"

,

"Wealth Management"

,

"Investment"

]

,

           

"Sports"

:

[

"Basketball"

,

"Soccer"

,

"Match"

,

"Goal"

]

,

           

"Technology"

:

[

"Mobile Phone"

,

"Computer"

,

"Programming"

,

"Tutorial"

]

,

           

"Entertainment"

:

[

"Movies"

,

"Music"

,

"Album"

,

"Song"

]

,

       

}

       

for

category

,

keywords

in

category_map.

items

(

)

:

           

if

any

(

keyword

in

text

for

keyword

in

keywords

)

:

               

return

{

                   

"category"

: category

,

                   

"confidence"

:

0.9

,

                   

"reasoning"

: f

"contains keywords: {', '.join([k for k in keywords if k in text])}"

               

}

       

return

{

"category"

:

"Other"

,

"confidence"

:

0.5

}

    test_texts

=

[

       

"Happy when stocks rise"

,

       

"The Football World Cup has started"

,

       

"RUNOOB's new programming tutorial"

,

   

]

categories

=

[

"Finance"

,

"Sports"

,

"Technology"

,

"Entertainment"

,

"Other"

]

   

for

text

in

test_texts:

        result

=

classify_with_llm

(

text

,

categories

)

       

print

(

f

"Text: {text}"

)

       

print

(

f

"Category: {result['category']}"

)

       

print

(

f

"Confidence: {result['confidence']:.4f}"

)

       

if

"reasoning"

in

result:

           

print

(

f

"Reason: {result['reasoning']}"

)

       

print

(

)

============================================

Run demonstration

============================================

if

name

==

"main"

:

    traditional_text_classification_demo

(

)

   

print

(

"="

50

)

llm_based_classification_demo

(

)

Few-shot classification method

Few-Shot Learning is a new capability brought by large models—the model can learn classification just by being given a few examples.

For example:

Text: This product is very useful -> Label: Positive

Text: The quality is too poor -> Label: Negative

Text: [Your new text] → Label: ?

The large model can understand the task from these two examples and make a reasonable classification for the new text.

Choosing between large models and small models

When to use which solution? Here is a decision guide:

Scenario Recommended solution Reason
Small data volume (< 1000 entries) Large model few-shot learning Small models cannot learn, large models have strong generalization ability
Large data volume (> 10000 entries) Fine-tuning small models (e.g., BERT) Lower cost, faster inference
Need quick verification Large model API No training required, immediately available
Production environment, high throughput Fine-tuning small models + distillation Fast inference speed, controllable cost
Categories change frequently Large model Prompt Engineering No need to retrain, just modify the prompt

Named Entity Recognition (NER)

Named Entity Recognition (Named Entity Recognition, NER) is finding specific entities in text, such as names of people, places, or organizations.

Sequence Labeling Framework

NER is usually modeled as a "sequence labeling" task: assigning a label to each word to indicate whether it is part of an entity.

For example, the sentence: "Zhang San works at Google", the labeling might be:

Zhang San -> B-PER (Person name start)

in -> O (Not an entity)

Google -> B-ORG (Organization start)

works -> O

BIO labeling format

The most commonly used annotation format is BIO:

B-XXX: Entity beginning

I-XXX: Inside entity

O: Not an entity

For example, for "Wang Xiao Ming works at Microsoft in Beijing", the annotation is:

Wang -> B-PER

Xiao -> I-PER

Ming -> I-PER

In

B-LOC

I-LOC

O

B-ORG

I-ORG

I-ORG

I-ORG

Up → O

Class → O

Practical Applications

Let's do NER with Hugging Face:

Example

============================================

NER Practice: Performing Named Entity Recognition with Hugging Face

============================================

def

ner_with_huggingface

(

)

:

   

"""Use pre-trained NER model"""

   

print

(

"NER Practical: Hugging Face"

)

   

print

(

"-"

50

)

   

try

:

       

from

transformers

import

pipeline

       

Load NER pipeline

       

English NER

ner_pipeline

=

pipeline

(

           

"ner"

,

model

=

"dbmdz/bert-large-cased-finetuned-conll03-english"

,

grouped_entities

=

True

 

Merge multiple tokens of the same entity

       

)

test_text

=

"John Smith works at Google in New York City. He loves RUNOOB tutorials."

results

=

ner_pipeline

(

test_text

)

       

print

(

f

"Text: {test_text}"

)

       

print

(

"Identified entities:"

)

       

for

entity

in

results:

           

print

(

f

" - {entity['word']}: {entity['entity_group']} (confidence: {entity['score']:.4f})"

)

       

print

(

)

   

except

Exception

as

e:

       

print

(

f

"You need to install transformers first: pip install transformers"

)

       

print

(

f

"Error: {e}"

)

============================================

Chinese NER: Using regex + keywords (simple scenarios)

============================================

def

simple_chinese_ner

(

)

:

   

"""Simple Chinese NER: Using regular expressions and dictionaries"""

   

import

re

   

print

(

"Simple Chinese NER: Regex + Dictionary"

)

   

print

(

"-"

50

)

   

Entity dictionary (will be larger in actual scenarios)

person_names

=

[

"Zhang San"

,

"Li Si"

,

"Wang Xiaoming"

,

"Andy Lau"

]

organizations

=

[

"Google"

,

"Microsoft"

,

"Alibaba"

,

"Tencent"

,

"RUNOOB"

]

locations

=

[

"Beijing"

,

"Shanghai"

,

"Shenzhen"

,

"New York"

,

"London"

]

   

Regular expression mode

patterns

=

{

       

"PERSON"

:

"|"

.

join

(

re

.

escape

(

name

)

for

name

in

person_names

)

,

       

"ORG"

:

"|"

.

join

(

re

.

escape

(

org

)

for

org

in

organizations

)

,

       

"LOC"

:

"|"

.

join

(

re

.

escape

(

loc

)

for

loc

in

locations

)

,

       

"PHONE"

: r

"1[3-9]\d{9}"

,

 

Phone number

       

"EMAIL"

: r

"\w+@\w+.\w+"

,

 

Email

   

}

   

def

extract_entities

(

text:

str

)

:

       

"""Extract entities from text"""

entities

=

[

]

       

for

entity_type

,

pattern

in

patterns.

items

(

)

:

           

for

match

in

re

.

finditer

(

pattern

,

text

)

:

entities.

append

(

{

                   

"text"

: match.

group

(

)

,

                   

"type"

: entity_type

,

                   

"start"

: match.

start

(

)

,

                   

"end"

: match.

end

(

)

,

               

}

)

       

Sort by position

entities.

sort

(

key

=

lambda

x: x

[

"start"

]

)

       

return

entities

   

Test

test_texts

=

[

       

"Zhang San works at Google, phone number is 13800138000"

,

       

"Wang Xiaoming went on a business trip to Microsoft in Beijing"

,

       

"If you have any questions, contact support@runoob.com"

,

       

"RUNOOB is a great learning website"

,

   

]

   

for

text

in

test_texts:

entities

=

extract_entities

(

text

)

       

print

(

f

"Text: {text}"

)

       

if

entities:

           

print

(

"Identified entities:"

)

           

for

ent

in

entities:

               

print

(

f

" - {ent['text']}: {ent['type']}"

)

       

else

:

           

print

(

"Entity not recognized"

)

       

print

(

)

============================================

Large model for NER

============================================

def

ner_with_llm

(

)

:

   

"""Demonstration of the approach to use large models for NER"""

   

print

(

"Large model for NER (demonstration approach)"

)

   

print

(

"-"

50

)

   

def

extract_entities_with_llm

(

text:

str

)

:

       

"Using LLM for NER (simulation)"

       

Real-world scenario: Constructing a prompt to call LLM

       

prompt = f"""Please extract named entities from the following text.

       

Only return JSON format, including entity types: PERSON (person's name), ORG (organization), LOC (location).

       

Text: {text}"""

       

Perform a simple simulation here

entities

=

[

]

       

Simple keyword matching to simulate

       

if

"Zhang San"

in

text:

entities.

append

(

{

"text"

:

"Zhang San"

,

"type"

:

"PERSON"

}

)

       

if

"Google"

in

text:

entities.

append

(

{

"text"

:

"Google"

,

"type"

:

"ORG"

}

)

       

if

"Beijing"

in

text:

entities.

append

(

{

"text"

:

"Beijing"

,

"type"

:

"LOC"

}

)

       

if

"RUNOOB"

in

text:

entities.

append

(

{

"text"

:

"RUNOOB"

,

"type"

:

"ORG"

}

)

       

return

entities

test_text

=

"Zhang San works at Google in Beijing, and he often studies on RUNOOB"

entities

=

extract_entities_with_llm

(

test_text

)

   

print

(

f

"Text: {test_text}"

)

   

print

(

"Identified entities:"

)

   

for

ent

in

entities:

       

print

(

f

" - {ent['text']}: {ent['type']}"

)

============================================

Run Demo

============================================

if

name

==

"main"

:

simple_chinese_ner

(

)

   

print

(

"="

50

)

ner_with_llm

(

)


Machine Translation

Machine translation is one of the most classic applications of NLP, and also one of the earliest commercialized applications.

Principles of Neural Machine Translation

Early machine translation was rule-based, later statistical, and now it is all neural.

Neural Machine Translation (NMT) is usually an Encoder-Decoder architecture:

  1. The Encoder reads the source language sentence and generates a semantic representation

  2. The Decoder generates the target language sentence based on the semantic representation

The attention mechanism allows the decoder to "focus" on different positions of the source language sentence when generating each word—this is key to improving translation quality.

Evaluation Metric: BLEU Score

How to measure translation quality? BLEU (Bilingual Evaluation Understudy) is the most commonly used metric.

The core idea of BLEU is: the higher the n-gram overlap between the machine translation result and the human translation result, the better the quality.

The BLEU score ranges from 0 to 1, and higher is better. Generally:

Below 0.1: Basically unintelligible

0.1-0.3: The general meaning can be understood

0.3-0.5: The translation quality is good

0.5 or higher: close to human translation

Example

============================================

BLEU score calculation demonstration

============================================

def

bleu_score_demo

(

)

:

   

"""Demonstrate BLEU score calculation"""

   

print

(

"BLEU Score Demonstration"

)

   

print

(

"-"

50

)

   

Note: It is recommended to use the sacrebleu library in actual use

   

This is a conceptual demonstration

   

from

collections

import

Counter

   

import

math

   

def

compute_ngrams

(

tokens

,

n

)

:

       

"""Calculate n-gram"""

       

return

[

tuple

(

tokens

[

i:i+n

]

)

for

i

in

range

(

len

(

tokens

)

-n+

1

)

]

   

def

simple_bleu

(

reference:

str

,

candidate:

str

,

max_n:

int

=

4

)

:

       

"""Simple BLEU calculation (conceptual demonstration)"""

ref_tokens

=

reference.

split

(

)

cand_tokens

=

candidate.

split

(

)

       

Calculate brevity penalty

ref_len

=

len

(

ref_tokens

)

cand_len

=

len

(

cand_tokens

)

       

if

cand_len

==

0

:

           

return

0.0

       

if

cand_len

<=

ref_len:

bp

=

math

.

exp

(

1

)

       

else

:

bp

=

1.0

       

Calculate the precision of each n-gram

precisions

=

[

]

       

for

n

in

range

(

1

,

max_n +

1

)

:

ref_ngrams

=

Counter

(

compute_ngrams

(

ref_tokens

,

n

)

)

cand_ngrams

=

Counter

(

compute_ngrams

(

cand_tokens

,

n

)

)

           

if

not

cand_ngrams:

precisions.

append

(

0.0

)

               

continue

           

Count the number of matches

matches

=

0

           

for

ngram

,

count

in

cand_ngrams.

items

(

)

:

matches +

=

min

(

count

,

ref_ngrams.

get

(

ngram

,

0

)

)

total

=

sum

(

cand_ngrams.

values

(

)

)

precisions.

append

(

matches / total

if

total

0

else

0.0

)

       

Geometric mean

       

if

all

(

p

==

0

for

p

in

precisions

)

:

geo_mean

=

0.0

       

else

:

           

Avoid log(0)

log_sum

=

sum

(

math

.

log

(

p +

1e-10

)

for

p

in

precisions

)

/ max_n

geo_mean

=

math

.

exp

(

log_sum

)

bleu

=

bp * geo_mean

       

return

bleu

   

Test

reference

=

"the cat sat on the mat"

candidates

=

[

       

"the cat sat on the mat"

,

 

Exact match

       

"the cat was on the mat"

,

 

Different words

       

"the cat sat on a mat"

,

   

Different articles

       

"a cat sat on the mat"

,

       

"the dog sat on the mat"

,

 

One word error

       

"mat the on sat cat the"

,

 

The order is completely mixed up

       

"hello world"

,

           

Completely unrelated

   

]

   

print

(

f

"Reference translation: {reference}"

)

   

print

(

)

   

for

candidate

in

candidates:

bleu

=

simple_bleu

(

reference

,

candidate

)

       

print

(

f

"Candidate translation: {candidate}"

)

       

print

(

f

"BLEU Score: {bleu:.4f}"

)

       

print

(

)

   

Chinese example

   

print

(

"Chinese translation example:"

)

   

print

(

"-"

30

)

ref

=

"I like to eat apples"

cand1

=

"I like to eat apples"

cand2

=

"I love to eat apples"

cand3

=

"Apple I like to eat"

   

print

(

f

"Reference: {ref}"

)

   

print

(

f

"Candidate 1: {cand1}, BLEU: {simple_bleu(ref, cand1):.4f}"

)

   

print

(

f

"Candidate 2: {cand2}, BLEU: {simple_bleu(ref, cand2):.4f}"

)

   

print

(

f

"Candidate 3: {cand3}, BLEU: {simple_bleu(ref, cand3):.4f}"

)

if

name

==

"main"

:

bleu_score_demo

(

)

Translation Quality in the LLM Era

After the emergence of large models, the quality of machine translation has reached a new level.

Traditional translation models are trained on bilingual parallel data, while large models are trained on massive amounts of text, leading to a deeper understanding of language.

Advantages of large models in translation:

  1. Better context understanding: can handle ambiguity and polysemy

  2. Style control: can specify the tone and style of the translation

  3. Terminology consistency: can provide a glossary to ensure consistent translation of proper nouns

  4. Multilingual capability: one model can perform mutual translation between dozens or hundreds of languages


Sentiment analysis

Sentiment analysis is determining the emotional tendency of text—positive, negative, or neutral.

Fine-grained sentiment analysis

Simple sentiment analysis is binary (positive/negative); more granular options include:

  1. Sentiment scoring: 1-5 stars, where 1 is the most negative and 5 is the most positive.

  2. Sentiment classification: anger, joy, sadness, surprise, etc.

  3. Aspect-Based Sentiment Analysis (ABSA): not only judges the overall sentiment but also analyzes the sentiment towards specific aspects.

For example: "The food at this restaurant is delicious, but the service is too slow."

Overall sentiment: neutral leaning positive

Aspect-level sentiment:

Dish → positive

Service -> Negative

Multilingual sentiment model

The current sentiment model can handle multiple languages without needing separate training for each language.

Commonly used multilingual models:

Large models such as XLM-RoBERTa, mBERT (Multilingual BERT), Llama, and Claude.


Text summarization

Text summarization is shortening long texts while retaining core information.

Extractive vs generative summarization

There are two main summarization methods:

Extractive summarization: Selects the most important sentences from the original text and stitches them together.

Advantage: Information is accurate and does not fabricate.

Disadvantage: Not very fluent and may contain redundant information.

Abstractive summarization: Allows the model to "understand" the original text and then write the summary in its own words.

Advantage: Fluent and concise, can summarize the original text.

Drawbacks: may "hallucinate" and fabricate information not in the original text

In the era of large models, generative summarization has become mainstream, but hallucination issues need to be considered when using it.

ROUGE evaluation metric

How to evaluate summary quality? ROUGE is the most commonly used metric.

There are several variants of ROUGE:

ROUGE-1: matching based on unigrams (single words)

ROUGE-2: matching based on bigrams (two words)

ROUGE-L: based on the longest common subsequence

Similar to BLEU, ROUGE also measures the overlap between machine-generated summaries and human reference summaries.

Example

============================================

Text Summarization: ROUGE Metric + Simple Extractive Summarization

============================================

def

rouge_demo

(

)

:

   

"""ROUGE Metric Demonstration"""

   

print

(

"ROUGE Metric Demonstration"

)

   

print

(

"-"

50

)

   

from

collections

import

Counter

   

def

compute_rouge_1

(

reference:

str

,

candidate:

str

)

float

:

       

"""Calculate ROUGE-1 (unigram F1)"""

ref_tokens

=

reference.

split

(

)

cand_tokens

=

candidate.

split

(

)

       

if

not

ref_tokens

or

not

cand_tokens:

           

return

0.0

ref_counts

=

Counter

(

ref_tokens

)

cand_counts

=

Counter

(

cand_tokens

)

       

Calculate the number of matches

matches

=

0

       

for

token

,

count

in

cand_counts.

items

(

)

:

matches +

=

min

(

count

,

ref_counts.

get

(

token

,

0

)

)

precision

=

matches /

len

(

cand_tokens

)

recall

=

matches /

len

(

ref_tokens

)

       

if

precision + recall

==

0

:

           

return

0.0

f1

=

2

(

precision + recall

)

       

return

f1

   

def

compute_lcs

(

a:

list

,

b:

list

)

int

:

       

"Calculate the length of the longest common subsequence"

m

,

n

=

len

(

a

)

,

len

(

b

)

dp

=

[

[

0

]

(

n +

1

)

for

_

in

range

(

m +

1

)

]

       

for

i

in

range

(

1

,

m +

1

)

:

           

for

j

in

range

(

1

,

n +

1

)

:

               

if

a

[

i-

1

]

==

b

[

j-

1

]

:

dp

[

i

]

[

j

]

=

dp

[

i-

1

]

[

j-

1

]

1

               

else

:

dp

[

i

]

[

j

]

=

max

(

dp

[

i-

1

]

[

j

]

,

dp

[

i

]

[

j-

1

]

)

       

return

dp

[

m

]

[

n

]

   

def

compute_rouge_l

(

reference:

str

,

candidate:

str

)

float

:

       

"""Calculate ROUGE-L (Longest Common Subsequence F1)"""

ref_tokens

=

reference.

split

(

)

cand_tokens

=

candidate.

split

(

)

       

if

not

ref_tokens

or

not

cand_tokens:

           

return

0.0

lcs_len

=

compute_lcs

(

ref_tokens

,

cand_tokens

)

        precision

=

lcs_len /

len

(

cand_tokens

)

recall

=

lcs_len /

len

(

ref_tokens

)

       

if

precision + recall

==

0

:

           

return

0.0

f1

=

2

(

precision + recall

)

       

return

f1

   

Test

reference

=

"Natural language processing is an important branch of artificial intelligence, studying the interaction between computers and human language."

candidates

=

[

       

"Natural language processing is an important branch of artificial intelligence, studying the interaction between computers and human language."

,

 

Exact match

       

"Natural language processing studies the interaction between computers and human language, which is an important branch of artificial intelligence."

,

 

Sequential adjustment

       

Natural language processing is a branch of artificial intelligence that studies the interaction between computers and language.

,

 

Abbreviated version

       

"RUNOOB is a programming learning website."

,

 

Irrelevant

   

]

   

print

(

f

"Reference summary: {reference}"

)

   

print

(

)

   

for

candidate

in

candidates:

rouge1

=

compute_rouge_1

(

reference

,

candidate

)

rougel

=

compute_rouge_l

(

reference

,

candidate

)

       

print

(

f

"Candidate summary: {candidate}"

)

       

print

(

f

"ROUGE-1: {rouge1:.4f}"

)

       

print

(

f

"ROUGE-L: {rougel:.4f}"

)

       

print

(

)

def

simple_extractive_summarization

(

)

:

   

"""Simple extractive summarization: selects important sentences based on word frequency"""

   

print

(

"Simple extractive summarization demo"

)

   

print

(

"-"

50

)

   

import

re

   

from

collections

import

Counter

   

def

split_sentences

(

text:

str

)

list

:

       

"Simple Chinese sentence segmentation"

       

Segment by period, exclamation mark, or question mark

sentences

=

re

.

split

(

r

'[。!?]'

,

text

)

       

Filter empty strings

sentences

=

[

s.

strip

(

)

for

s

in

sentences

if

s.

strip

(

)

]

       

return

sentences

   

def

get_word_frequency

(

text:

str

)

Counter:

       

"""Calculate word frequency (simple demonstration: simulating with character-level n-gram)"""

       

In a real scenario, a word segmentation tool like jieba should be used

       

Here, we simply use uni-gram

chars

=

[

c

for

c

in

text

if

c.

strip

(

)

]

       

return

Counter

(

chars

)

   

def

sentence_score

(

sentence:

str

,

word_freq: Counter

)

float

:

       

"""Calculate sentence score"""

       

if

not

sentence:

           

return

0.0

       

Simple scoring: sum of word frequencies in the sentence / sentence length

total_score

=

0.0

       

for

char

in

sentence:

total_score +

=

word_freq.

get

(

char

,

0

)

       

Normalization

       

return

total_score /

(

len

(

sentence

)

1

)

   

def

extractive_summary

(

text:

str

,

num_sentences:

int

=

2

)

str

:

       

"""Extractive summary"""

        sentences

=

split_sentences

(

text

)

       

if

len

(

sentences

)

<=

num_sentences:

           

return

text

       

Calculate word frequency

word_freq

=

get_word_frequency

(

text

)

       

Calculate the score for each sentence

scores

=

[

(

i

,

sentence_score

(

s

,

word_freq

)

)

for

i

,

s

in

enumerate

(

sentences

)

]

       

Sort by score, select the highest few

scores.

sort

(

key

=

lambda

x: x

[

1

]

,

reverse

=

True

)

top_indices

=

[

i

for

i

,

score

in

scores

[

:num_sentences

]

]

top_indices.

sort

(

)

 

Maintain original order

       

Concatenate results

summary

=

.

.

join

(

sentences

[

i

]

for

i

in

top_indices

)

"."

       

return

summary

   

Test text

test_text

=

"""
Natural language processing is an important branch of artificial intelligence. It studies how to enable computers to understand and generate human language.
This technology has many applications, including machine translation, sentiment analysis, and question-answering systems.
In recent years, the emergence of large language models has brought about major breakthroughs in natural language processing.
The RUNOOB website provides many excellent programming tutorials to help developers learn new skills.
"""

   

print

(

"Original text:"

)

   

print

(

test_text.

strip

(

)

)

   

print

(

)

summary

=

extractive_summary

(

test_text

,

num_sentences

=

2

)

   

print

(

"Extractive summary:"

)

   

print

(

summary

)

if

name

==

"main"

:

rouge_demo

(

)

   

print

(

"="

50

)

simple_extractive_summarization

(

)