跳到主要内容自然语言处理技术与应用实践 | 极客日志PythonAI算法
自然语言处理技术与应用实践
本章介绍自然语言处理(NLP)的基础概念、文本表示方法及深度学习模型实现。涵盖文本分类、情感分析、命名实体识别等核心任务,展示基于 LSTM 和 BERT 等预训练模型的代码示例。同时探讨机器翻译、文本生成及问答系统的应用场景,并通过产品评论情感分析实战项目演示完整开发流程。最后总结数据预处理、模型优化及部署的最佳实践,介绍 RoBERTa 和小样本学习等前沿技术方向。
花里胡哨4.4K 浏览 第 12 章 自然语言处理技术与应用实践

学习目标
- 掌握自然语言处理(NLP)的基本概念和原理
- 了解 NLP 的常用任务和应用场景
- 学会使用深度学习框架实现 NLP 模型
- 掌握文本分类、情感分析、命名实体识别等任务的实现方法
- 学习 NLP 技术在实际项目中的应用实践
12.1 自然语言处理技术基础
12.1.1 自然语言处理的概念
自然语言处理(NLP)是计算机科学和人工智能的一个重要领域,研究如何让计算机理解和处理人类语言。
NLP 的主要任务
- 文本分类:将文本分为不同的类别
- 情感分析:分析文本的情感倾向
- 命名实体识别:识别文本中的命名实体(如人名、地名、组织名)
- 机器翻译:将一种语言的文本翻译成另一种语言
- 文本生成:生成新的文本
- 问答系统:根据问题回答相关内容
- 对话系统:与用户进行自然语言对话
12.1.2 文本表示
计算机无法直接处理文本,需要将文本转换为数字表示。常用的文本表示方法包括:
- 词袋模型(Bag of Words):将文本表示为词频向量
- TF-IDF:使用词频和逆文档频率加权的词向量
- 词嵌入(Word Embedding):将词表示为低维向量,捕捉词之间的语义关系
词袋模型的实现
from sklearn.feature_extraction.text import CountVectorizer
texts = [
'自然语言处理是计算机科学的一个分支',
'NLP 研究如何让计算机理解和处理人类语言',
'文本分类是 NLP 的一个常用任务'
]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
print('词汇表:', vectorizer.get_feature_names_out())
print('词频向量:\n', X.toarray())
💡 词袋模型简单直观,但无法捕捉词之间的语义关系。
12.1.3 词嵌入
词嵌入是 NLP 中的重要技术,将词表示为低维向量,捕捉词之间的语义关系。常用的词嵌入方法包括 Word2Vec、GloVe 等。
使用预训练词嵌入
gensim.models KeyedVectors
embedding_path =
word_vectors = KeyedVectors.load_word2vec_format(embedding_path, binary=, no_header=)
word =
word word_vectors:
vector = word_vectors[word]
()
:
()
similar_words = word_vectors.most_similar(, topn=)
()
from
import
'glove.6B.100d.txt'
False
True
'natural'
if
in
print
f"{word}的词向量:{vector}"
else
print
f"{word}不在词嵌入词汇表中"
'natural'
5
print
f"与'natural'相似的词:{similar_words}"
✅ 词嵌入可以捕捉词之间的语义关系,提高 NLP 任务的性能。
12.2 文本分类
12.2.1 文本分类的基本原理
文本分类是 NLP 的基础任务,其目标是将文本分为不同的类别。
- 数据预处理:对文本进行分词、去停用词等操作
- 文本表示:将文本转换为数字表示
- 模型训练:使用训练数据训练分类模型
- 模型评估:使用测试数据评估模型性能
12.2.2 文本分类模型实现
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout, Bidirectional
from tensorflow.keras.models import Sequential
import pandas as pd
data = pd.read_csv('text_classification_data.csv')
tokenizer = Tokenizer(num_words=10000)
tokenizer.fit_on_texts(data['text'])
X = tokenizer.texts_to_sequences(data['text'])
X = pad_sequences(X, maxlen=100)
y = data['label']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = Sequential([
Embedding(input_dim=10000, output_dim=64, input_length=100),
Bidirectional(LSTM(64)),
Dense(64, activation='relu'),
Dropout(0.5),
Dense(1, activation='sigmoid')
])
model.compile(
optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy']
)
history = model.fit(
X_train, y_train,
validation_data=(X_test, y_test),
epochs=10,
batch_size=32
)
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"Test accuracy: {test_acc}")
✅ 该模型使用了双向 LSTM 和嵌入层,实现了文本分类任务。
12.2.3 使用预训练语言模型
预训练语言模型(如 BERT、GPT)在 NLP 任务中取得了优异的性能,可以通过微调应用到文本分类任务中。
from transformers import BertTokenizer, TFBertForSequenceClassification
import tensorflow as tf
import pandas as pd
data = pd.read_csv('text_classification_data.csv')
tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')
max_length = 100
X_train_encoded = tokenizer(list(data['text']), max_length=max_length, padding=True, truncation=True, return_tensors='tf')
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X_train_encoded['input_ids'], data['label'], test_size=0.2, random_state=42)
model = TFBertForSequenceClassification.from_pretrained('bert-base-chinese', num_labels=2)
optimizer = tf.keras.optimizers.Adam(learning_rate=2e-5)
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')
model.compile(optimizer=optimizer, loss=loss, metrics=[metric])
history = model.fit(
X_train, y_train,
validation_data=(X_test, y_test),
epochs=3,
batch_size=8
)
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"Test accuracy: {test_acc}")
💡 预训练语言模型通过微调可以快速构建高性能的文本分类模型,但计算成本较高。
12.3 情感分析
12.3.1 情感分析的基本原理
情感分析是 NLP 的常见任务,其目标是分析文本的情感倾向(如正面、负面、中性)。
- 基于词典的方法:使用情感词典分析文本的情感倾向
- 机器学习方法:使用机器学习算法训练情感分析模型
- 深度学习的方法:使用深度学习模型(如 LSTM、BERT)进行情感分析
12.3.2 情感分析模型实现
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import pandas as pd
data = pd.read_csv('sentiment_analysis_data.csv')
tokenizer = Tokenizer(num_words=10000)
tokenizer.fit_on_texts(data['text'])
X = tokenizer.texts_to_sequences(data['text'])
X = pad_sequences(X, maxlen=100)
y = data['sentiment']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = tf.keras.Sequential([
tf.keras.layers.Embedding(input_dim=10000, output_dim=64, input_length=100),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(3, activation='softmax')
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
history = model.fit(
X_train, y_train,
validation_data=(X_test, y_test),
epochs=10,
batch_size=32
)
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"Test accuracy: {test_acc}")
new_text = ['这个产品非常好,质量很高', '这个产品质量很差,不值得购买']
new_text_encoded = tokenizer.texts_to_sequences(new_text)
new_text_padded = pad_sequences(new_text_encoded, maxlen=100)
predictions = model.predict(new_text_padded)
sentiments = ['负面', '中性', '正面']
for text, pred in zip(new_text, predictions):
sentiment = sentiments[pred.argmax()]
print(f"{text}: {sentiment}")
✅ 该模型使用了双向 LSTM 和嵌入层,实现了情感分析任务。
12.4 命名实体识别
12.4.1 命名实体识别的基本原理
命名实体识别(NER)是 NLP 的重要任务,其目标是识别文本中的命名实体(如人名、地名、组织名)。
- 基于规则的方法:使用正则表达式或语法规则识别命名实体
- 机器学习方法:使用条件随机场(CRF)或支持向量机(SVM)等算法
- 深度学习方法:使用双向 LSTM+CRF 或预训练语言模型(如 BERT)
12.4.2 命名实体识别模型实现
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout, Bidirectional, TimeDistributed
from tensorflow.keras.models import Sequential
import pandas as pd
data = pd.read_csv('ner_data.csv')
tokenizer = Tokenizer(num_words=10000)
tokenizer.fit_on_texts(data['text'])
X = tokenizer.texts_to_sequences(data['text'])
X = pad_sequences(X, maxlen=100)
label_tokenizer = Tokenizer()
label_tokenizer.fit_on_texts(data['labels'])
y = label_tokenizer.texts_to_sequences(data['labels'])
y = pad_sequences(y, maxlen=100)
y = tf.keras.utils.to_categorical(y)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = Sequential([
Embedding(input_dim=10000, output_dim=64, input_length=100),
Bidirectional(LSTM(64, return_sequences=True)),
TimeDistributed(Dense(64, activation='relu')),
Dropout(0.5),
TimeDistributed(Dense(y.shape[-1], activation='softmax'))
])
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
history = model.fit(
X_train, y_train,
validation_data=(X_test, y_test),
epochs=10,
batch_size=32
)
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"Test accuracy: {test_acc}")
✅ 该模型使用了双向 LSTM 和 TimeDistributed 层,实现了命名实体识别任务。
12.5 自然语言处理应用场景
12.5.1 机器翻译
机器翻译是 NLP 的经典任务,将一种语言的文本翻译成另一种语言。
from transformers import MarianMTModel, MarianTokenizer
import torch
model_name = 'Helsinki-NLP/opus-mt-zh-en'
tokenizer = MarianTokenizer.from_pretrained(model_name)
model = MarianMTModel.from_pretrained(model_name)
text = '自然语言处理是计算机科学的一个分支'
inputs = tokenizer(text, return_tensors='pt', padding=True, truncation=True)
with torch.no_grad():
outputs = model.generate(**inputs)
translation = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(f"原文:{text}")
print(f"译文:{translation}")
💡 Transformer 架构在机器翻译任务中取得了优异的性能,是目前主流的机器翻译方法。
12.5.2 文本生成
文本生成是 NLP 的重要任务,用于生成新的文本,如对话系统、文章生成等。
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import torch
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')
prompt = '自然语言处理是计算机科学的一个分支'
inputs = tokenizer(prompt, return_tensors='pt')
with torch.no_grad():
outputs = model.generate(**inputs, max_length=100, num_return_sequences=1)
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(f"生成的文本:{generated_text}")
✅ GPT-2 是一种强大的文本生成模型,能够生成流畅的自然语言文本。
12.5.3 问答系统
问答系统是 NLP 的应用之一,根据用户的问题回答相关内容。
from transformers import BertTokenizer, TFBertForQuestionAnswering
import tensorflow as tf
tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')
model = TFBertForQuestionAnswering.from_pretrained('bert-base-chinese')
question = '什么是自然语言处理?'
context = '自然语言处理是计算机科学的一个分支,研究如何让计算机理解和处理人类语言。'
inputs = tokenizer(question, context, return_tensors='tf')
with tf.no_grad():
outputs = model(**inputs)
start_logits = outputs.start_logits
end_logits = outputs.end_logits
start_index = tf.argmax(start_logits, axis=1)[0]
end_index = tf.argmax(end_logits, axis=1)[0]
answer = tokenizer.decode(inputs['input_ids'][0][start_index:end_index+1], skip_special_tokens=True)
print(f"问题:{question}")
print(f"答案:{answer}")
💡 BERT 在问答系统任务中取得了优异的性能,是目前主流的问答系统方法。
12.6 实战项目:产品评论情感分析系统
12.6.1 项目目标
开发一个产品评论情感分析系统,帮助用户分析产品评论的情感倾向。
12.6.2 项目步骤
- 数据收集与预处理
- 模型选择与训练
- 模型优化与评估
- 系统开发
- 部署与测试
12.6.3 项目代码
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import pandas as pd
import joblib
data = pd.read_csv('product_reviews.csv')
tokenizer = Tokenizer(num_words=10000)
tokenizer.fit_on_texts(data['review'])
X = tokenizer.texts_to_sequences(data['review'])
X = pad_sequences(X, maxlen=100)
y = data['sentiment']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = tf.keras.Sequential([
tf.keras.layers.Embedding(input_dim=10000, output_dim=64, input_length=100),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(3, activation='softmax')
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
history = model.fit(
X_train, y_train,
validation_data=(X_test, y_test),
epochs=10,
batch_size=32
)
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"Test accuracy: {test_acc}")
model.save('product_review_sentiment_analyzer.h5')
joblib.dump(tokenizer, 'tokenizer.pkl')
loaded_model = tf.keras.models.load_model('product_review_sentiment_analyzer.h5')
loaded_tokenizer = joblib.load('tokenizer.pkl')
new_reviews = ['这个产品非常好,质量很高', '这个产品质量很差,不值得购买']
new_reviews_encoded = loaded_tokenizer.texts_to_sequences(new_reviews)
new_reviews_padded = pad_sequences(new_reviews_encoded, maxlen=100)
predictions = loaded_model.predict(new_reviews_padded)
sentiments = ['负面', '中性', '正面']
for review, pred in zip(new_reviews, predictions):
sentiment = sentiments[pred.argmax()]
print(f"{review}: {sentiment}")
✅ 该项目实现了一个产品评论情感分析系统,使用 LSTM 模型和词嵌入技术。
12.7 自然语言处理技术前沿
12.7.1 预训练语言模型
预训练语言模型(如 BERT、GPT、RoBERTa)在 NLP 任务中取得了优异的性能,成为 NLP 研究的热点。
from transformers import RobertaTokenizer, TFRobertaForSequenceClassification
import tensorflow as tf
import pandas as pd
data = pd.read_csv('text_classification_data.csv')
tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
max_length = 100
X_train_encoded = tokenizer(list(data['text']), max_length=max_length, padding=True, truncation=True, return_tensors='tf')
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X_train_encoded['input_ids'], data['label'], test_size=0.2, random_state=42)
model = TFRobertaForSequenceClassification.from_pretrained('roberta-base', num_labels=2)
optimizer = tf.keras.optimizers.Adam(learning_rate=2e-5)
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy')
model.compile(optimizer=optimizer, loss=loss, metrics=[metric])
history = model.fit(
X_train, y_train,
validation_data=(X_test, y_test),
epochs=3,
batch_size=8
)
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"Test accuracy: {test_acc}")
💡 RoBERTa 是 BERT 的改进版本,通过优化预训练过程提高了性能。
12.7.2 小样本学习
小样本学习(Few-Shot Learning)是 NLP 研究的重要方向,目标是在少量标注数据的情况下训练高性能模型。
from transformers import T5Tokenizer, T5ForConditionalGeneration
import torch
tokenizer = T5Tokenizer.from_pretrained('t5-small')
model = T5ForConditionalGeneration.from_pretrained('t5-small')
train_data = [
('The quick brown fox jumps over the lazy dog.', 'Animal'),
('Python is a popular programming language.', 'Technology'),
('Paris is the capital of France.', 'Geography')
]
train_inputs = []
train_targets = []
for text, label in train_data:
input_text = f'classify: {text}'
target_text = label
train_inputs.append(input_text)
train_targets.append(target_text)
train_encoded = tokenizer(train_inputs, return_tensors='pt', padding=True, truncation=True)
train_target_encoded = tokenizer(train_targets, return_tensors='pt', padding=True, truncation=True)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
loss_fn = torch.nn.CrossEntropyLoss()
for epoch in range(10):
optimizer.zero_grad()
outputs = model(**train_encoded, labels=train_target_encoded['input_ids'])
loss = outputs.loss
loss.backward()
optimizer.step()
print(f"Epoch {epoch+1}, Loss: {loss.item()}")
test_text = 'The sun is shining in the sky.'
input_text = f'classify: {test_text}'
input_encoded = tokenizer(input_text, return_tensors='pt')
with torch.no_grad():
outputs = model.generate(**input_encoded)
prediction = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(f"Test text: {test_text}")
print(f"Prediction: {prediction}")
✅ 小样本学习可以在少量标注数据的情况下训练模型,适用于数据标注成本高的场景。
12.8 工程实践最佳实践
12.8.1 数据预处理
- 对文本进行分词、去停用词等操作
- 处理数据不平衡问题
- 确保数据格式正确
12.8.2 模型选择与优化
- 根据任务选择合适的模型
- 使用预训练模型进行微调
- 对模型进行压缩和量化
12.8.3 部署与监控
12.9 总结
在本章中,我们学习了自然语言处理技术与应用实践,包括文本分类、情感分析、命名实体识别等任务的实现方法,以及自然语言处理技术在机器翻译、文本生成、问答系统等场景中的应用。我们还介绍了自然语言处理技术的前沿研究,如预训练语言模型和小样本学习。最后,我们通过实战项目演示了如何开发一个产品评论情感分析系统。自然语言处理技术在各个领域的应用越来越广泛,为人类生活带来了很大的便利。
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
- RSA密钥对生成器
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
- Mermaid 预览与可视化编辑
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
- 随机西班牙地址生成器
随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online
- Gemini 图片去水印
基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
- curl 转代码
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online