基本介绍
自然语言处理 (NLP) 是一个专注于计算机与人类语言之间交互的研究领域。它涉及教计算机以对人们有意义和有用的方式理解、解释和生成人类语言。NLP 是人工智能 (AI) 的一个子领域,近年来受到了极大的关注。
自然语言处理是一门融语言学、计算机科学、数学于一体的科学。因此,这一领域的研究将涉及自然语言,即人们日常使用的语言,所以它与语言学的研究有着密切的联系,但又有重要的区别。自然语言处理并不是一般地研究自然语言,而在于研制能有效地实现自然语言通信的计算机系统,特别是其中的软件系统。因而它是计算机科学的一部分。
定义与背景
NLP大模型是指通过大规模预训练和自监督学习技术构建的深度学习模型,旨在提高计算机对自然语言的理解和生成能力。这类模型通常具有数以亿计的参数,能够处理复杂的语言任务。其起源可以追溯到2017年,当时Google发布了Transformer模型,该模型为后续的NLP大模型发展奠定了基础。
基础技术
- 分词:基本算是所有NLP任务中最底层的技术。不论解决什么问题,分词永远是第一步。
- 词性标注:判断文本中的词的词性(名词、动词、形容词等等),一般作为额外特征使用。
- 句法分析:分为句法结构分析和依存句法分析两种。
- 词干提取:从单词各种前缀后缀变化、时态变化等变化中还原词干,常见于英文文本处理。
- 命名实体识别:识别并抽取文本中的实体,一般采用BIO形式。
- 指代消歧:文本中的代词,如“他”“这个”等,还原成其所指实体。
- 关键词抽取:提取文本中的关键词,用以表征文本或下游应用。
- 词向量与词嵌入:把单词映射到低维空间中,并保持单词间相互关系不变。是NLP深度学习技术的基础。
- 文本生成:给定特定的文本输入,生成所需要的文本,主要应用于文本摘要、对话系统、机器翻译、问答系统等领域。
NLP 的工作原理
NLP 涉及处理和分析人类语言的几个步骤。第一步是将文本分解为更小的单元,例如单词和短语。此过程称为分词化。文本被标记化后,下一步是为每个单词分配含义。此过程称为命名实体识别 (NER)。
NLP 的另一个重要方面是词性标记,它涉及识别句子中每个单词的语法功能。这对于理解句子的上下文和结构很有用。NLP 还涉及机器学习算法(如聚类和分类)来分析和分类文本数据。
NLP 的应用
NLP 在各个行业都有众多应用。最常见的应用之一是情绪分析,它涉及分析客户评论和社交媒体帖子以了解对产品或品牌的情绪。NLP 还用于聊天机器人和虚拟助手,以帮助用户以更自然的方式与机器交互。
NLP 的其他应用包括机器翻译、语音识别和文本摘要。NLP 还用于医疗保健,以分析电子病历并协助临床决策。在法律行业,NLP 用于电子取证和合同分析。
学习自然语言处理的步骤
- 学习编程和数据结构的基础知识。
- 学习 Python,这是 NLP 最流行的语言。
- 了解文本预处理技术,例如分词化、词干提取和非索引字删除。
- 了解文本表示技术,例如词袋和 TF-IDF。
- 了解流行的 NLP 库,例如 NLTK、spaCy 和 Gensim。
- 了解适用于 NLP 的机器学习算法,例如 Naive Bayes、Support Vector Machines 和 Random Forests。
- 了解 NLP 的深度学习技术,例如递归神经网络 (RNN) 和 Transformers。
- 了解常见的 NLP 任务,例如情绪分析、命名实体识别和机器翻译。
- 参与实践项目以应用您的知识并培养实践技能。
- 及时了解 NLP 的最新研究和趋势。
开始
对于此 NLP 教程,您需要安装 Python 以及本指南中使用的最流行的自然语言处理库。
打开终端并键入(可能需要一段时间才能运行):
pip install nltk
pip install -U scikit-learn
pip install gensim
pip install networkx
pip install googletrans==4.0.0-rc1
pip install graphviz
pip3 install chatterbot
pip install -U pip setuptools wheel
pip install -U spacy
python -m spacy download en_core_web_sm
什么是分词化
分词是将大文本分解为称为分词的小块的过程。这些标记通常是单词、短语或句子。标记化是许多自然语言处理 (NLP) 任务中的关键步骤。
以下是一些示例 Python 代码,用于说明使用流行的 NLTK 库进行分词:
import nltk
nltk.download('punkt')
text = "Tokenization is the process of breaking down a large text into smaller chunks called tokens. These tokens are usually words, phrases, or sentences."
tokens = nltk.word_tokenize(text)
print(tokens)
您将在输出中看到一个 Python 列表,其中句子被拆分为标记。
['Tokenization', 'is', 'the', 'process', 'of', 'breaking', 'down', 'a', 'large', 'text', 'into', 'smaller', 'chunks', 'called', 'tokens', '.', 'These', 'tokens', 'are', 'usually', 'words', ',', 'phrases', ',', 'or', 'sentences', '.']
可视化标记化。
import nltk
import matplotlib.pyplot as plt
nltk.download('punkt')
text = "Tokenization is the process of breaking down a large text into smaller chunks called tokens. These tokens are usually words, phrases, or sentences."
tokens = nltk.word_tokenize(text)
freq_dist = nltk.FreqDist(tokens)
freq_dist.plot(30)
此代码创建标记的频率分布,并在直方图中绘制 30 个最常见的标记。这种可视化可以帮助我们更好地理解文本的结构和内容。
什么是词性标记
词性 (POS) 标记是用相应的词性(例如名词、动词、形容词或副词)标记句子中的每个单词的过程。此信息用于许多自然语言处理任务,例如信息检索、机器翻译和情感分析。
以下是一些示例 Python 代码,用于说明使用流行的 NLTK 库进行 POS 标记:
import nltk
nltk.download('averaged_perceptron_tagger')
text = "Tokenization is the process of breaking down a large text into smaller chunks called tokens."
tokens = nltk.word_tokenize(text)
pos_tags = nltk.pos_tag(tokens)
print(pos_tags)
在输出中,您将看到一个令牌列表,但这次,POS 标签将作为 Python 元组与令牌一起添加。如果您不知道这些是什么意思,请务必阅读我们关于 nltk POS 标签的博客文章。
[('Tokenization', 'NN'), ('is', 'VBZ'), ('the', 'DT'), ('process', 'NN'), ('of', 'IN'), ('breaking', 'VBG'), ('down', 'RP'), ('a', 'DT'), ('large', 'JJ'), ('text', 'NN'), ('into', 'IN'), ('smaller', 'JJR'), ('chunks', 'NNS'), ('called', 'VBD'), ('tokens', 'NNS'), ('.', '.')]
可视化词性标记。
import nltk
import matplotlib.pyplot as plt
nltk.download('averaged_perceptron_tagger')
text = "Tokenization is the process of breaking down a large text into smaller chunks called tokens."
tokens = nltk.word_tokenize(text)
pos_tags = nltk.pos_tag(tokens)
pos_freq = {}
for tag in pos_tags:
pos = tag[1]
if pos in pos_freq:
pos_freq[pos] += 1
else:
pos_freq[pos] = 1
labels = pos_freq.keys()
sizes = pos_freq.values()
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.axis('equal')
plt.show()
此代码创建词性标签的频率分布,并将其绘制在饼图中。这种可视化可以帮助我们理解文本中不同词性的分布。
什么是词干提取
词干提取是将变形词减少到其基本或词根形式的过程,通常会导致创建可能不是实际单词的单词。例如,“jumping”、“jumps”、“jumped”在词干提取后都变成了“jump”。
在 Python 中,NLTK 库提供了一个可以执行词干提取的词干分析器模块。下面是一个示例代码,用于说明如何使用 Porter Stemmer 进行词干提取:
from nltk.stem import PorterStemmer
stemmer = PorterStemmer()
words = ["jumping", "jumps", "jumped"]
stemmed_words = [stemmer.stem(word) for word in words]
print(stemmed_words)
该代码生成一个输出,将列表的每个单词都显示到其词干版本中,这表明它们都具有相同的词干。
['jump', 'jump', 'jump']
可视化词干提取。此代码将生成一个条形图,显示每个词干的出现频率:
import matplotlib.pyplot as plt
word_freq = {"jumping": 5, "jumps": 3, "jumped": 2, "jumper": 1, "jumpers": 4, "jumpiest": 1, "jumpingly": 2, "jumpiness": 3}
stemmed_word_freq = {}
for word, freq in word_freq.items():
stemmed_word = stemmer.stem(word)
stemmed_word_freq[stemmed_word] = stemmed_word_freq.get(stemmed_word, 0) + freq
plt.bar(stemmed_word_freq.keys(), stemmed_word_freq.values())
plt.xlabel("Stemmed words")
plt.ylabel("Frequency")
plt.show()
输出显示每个字干的频率。
什么是情感分析
情感分析是从给定文本中识别和提取观点或情感的过程。它涉及将文本的极性分类为正、负或中性。这项技术有许多应用,包括市场研究、客户服务和社交媒体分析。
在 Python 中,NLTK 库提供了一个情感分析模块,该模块使用 VADER(Valence Aware Dictionary and sEntiment Reasoner)词典来执行情感分析。下面是一个示例代码,用于说明使用 VADER 模块进行情感分析:
import nltk
from nltk.sentiment import SentimentIntensityAnalyzer
nltk.download('vader_lexicon')
text = "I love this product! It's the best one I've ever used."
analyzer = SentimentIntensityAnalyzer()
scores = analyzer.polarity_scores(text)
print(scores)
polarity_scores() 方法返回一个字典,其中包含消极、中性、积极和复合情绪的分数。复合分数是一个范围从 -1(最负面)到 1(最正面)的指标。
{'neg': 0.0, 'neu': 0.479, 'pos': 0.521, 'compound': 0.8655}
为了可视化情绪评分,我们可以使用 Matplotlib 的饼图:
import matplotlib.pyplot as plt
labels = ['Negative', 'Neutral', 'Positive']
sizes = [scores['neg'], scores['neu'], scores['pos']]
colors = ['red', 'yellow', 'green']
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%')
plt.axis('equal')
plt.show()
什么是文本分类
文本分类是一种常见的 NLP 任务,其中给定的文本文档被分类为预定义的类别。例如,垃圾邮件检测是文本分类的一个示例,其中的任务是将电子邮件分类为垃圾邮件或非垃圾邮件。
下面是一个简短的 Python 代码来说明文本分类:
# Import the necessary libraries
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, confusion_matrix
# Load the dataset
newsgroups = fetch_20newsgroups(subset='all')
X = newsgroups.data
y = newsgroups.target
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Vectorize the text data
vectorizer = TfidfVectorizer()
X_train_vect = vectorizer.fit_transform(X_train)
X_test_vect = vectorizer.transform(X_test)
# Train the model
model = MultinomialNB()
model.fit(X_train_vect, y_train)
# Predict on the test set
y_pred = model.predict(X_test_vect)
# Evaluate the performance
print('Accuracy:', accuracy_score(y_test, y_pred))
print('Confusion matrix:', confusion_matrix(y_test, y_pred))
上面的代码加载垃圾邮件数据集,预处理文本数据,使用 TfidfVectorizer 对文本数据进行矢量化,在训练集上训练 Naive Bayes 分类器,并在测试集上进行预测。最后,它使用准确性和混淆矩阵评估性能。
这个输出不是那么漂亮,我们可以使用该方法对其进行改进。plot_confusion_matrix
# Import the necessary libraries
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, confusion_matrix, plot_confusion_matrix
# Load the dataset
newsgroups = fetch_20newsgroups(subset='all')
X = newsgroups.data
y = newsgroups.target
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Vectorize the text data
vectorizer = TfidfVectorizer()
X_train_vect = vectorizer.fit_transform(X_train)
X_test_vect = vectorizer.transform(X_test)
# Train the model
model = MultinomialNB()
model.fit(X_train_vect, y_train)
# Predict on the test set
y_pred = model.predict(X_test_vect)
# Evaluate the performance
print('Accuracy:', accuracy_score(y_test, y_pred))
print('Confusion matrix:')
plot_confusion_matrix(model, X_test_vect, y_test)
plt.show()
什么是语言建模
语言建模是预测给定前一个单词的序列中下一个单词的概率的任务。它涉及构建语言统计模型,该模型可用于生成文本或对文本进行预测。语言建模是许多自然语言处理任务的关键组成部分,例如语音识别、机器翻译和文本生成。
下面是一个简短的 Python 代码,用于使用自然语言工具包 (NLTK) 库训练简单的语言模型:
import nltk
from nltk.corpus import gutenberg
nltk.download('gutenberg')
# Load the text corpus
corpus = gutenberg.words('austen-emma.txt')
# Create a list of sentences
sentences = nltk.sent_tokenize(' '.join(corpus))
# Preprocess the sentences
preprocessed = []
for sentence in sentences:
tokens = nltk.word_tokenize(sentence.lower())
preprocessed.append(tokens)
# Train a bigram language model
model = nltk.BigramAssocMeasures()
finder = nltk.BigramCollocationFinder.from_documents(preprocessed)
finder.apply_freq_filter(5)
bigrams = finder.nbest(model.pmi, 20)
# Print the most frequent bigrams
print(bigrams)
此代码从 NLTK 库加载文本语料库,通过对句子进行分词和小写对其进行预处理,并使用逐点互信息 (PMI) 度量训练二元语法语言模型。然后打印最常见的二元语法。
[('brunswick', 'square'), ('sore', 'throat'), ('mill', 'farm'), ('william', 'larkins'), ('baked', 'apples'), ('box', 'hill'), ('sixteen', 'miles'), ('maple', 'grove'), ('hair', 'cut'), ('south', 'end'), ('colonel', 'campbell'), ('protest', 'against'), ('robert', 'martin'), ('vast', 'deal'), ('five', 'couple'), ('ready', 'wit'), ('musical', 'society'), ('infinitely', 'superior'), ('donwell', 'abbey'), ('married', 'women')]
为了可视化语言模型,我们可以使用 NetworkX 库创建二元语法的网络图:
import networkx as nx
import matplotlib.pyplot as plt
# Create a network graph of the bigrams
graph = nx.Graph()
for bigram in bigrams:
graph.add_edge(bigram[0], bigram[1])
# Draw the network graph
pos = nx.spring_layout(graph)
nx.draw_networkx_nodes(graph, pos, node_size=200, node_color='lightblue')
nx.draw_networkx_edges(graph, pos, width=1, alpha=0.5, edge_color='gray')
nx.draw_networkx_labels(graph, pos, font_size=10, font_family='sans-serif')
plt.axis('off')
plt.show()
什么是机器翻译
机器翻译是自然语言处理的一个子领域,专注于使用机器学习算法自动将文本从一种语言翻译成另一种语言。它涉及处理输入文本,生成其含义的表示形式,然后使用该表示形式以另一种语言生成相应的文本。
为了说明 Python 中的机器翻译,我们可以使用 Googletrans 库,它为 Google Translate API 提供了一个简单的接口。下面是一个使用 Googletrans 将句子从英语翻译成中文的示例代码:
from googletrans import Translator
translator = Translator(service_urls=[''])
text = "Hello, how are you today?"
translation = translator.translate(text, dest='CN')
print(translation.text)
翻译输出:
你好,你今天怎么样?
什么是 NLP 中的问答?
问答 (QA) 是一项 NLP 任务,其目标是为以自然语言提出的问题找到答案。这项任务涉及语言理解和信息检索技术。
为了说明 Python 中的问答,我们可以使用自然语言工具包 (NLTK) 库。下面是一个示例:
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('stopwords')
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
# Define the passage to search for answers
passage = "The quick brown fox jumps over the lazy dog. The dog, who was not very impressed by the fox, barked loudly and chased it away."
# Tokenize the passage into sentences
sentences = sent_tokenize(passage)
# Define the question to answer
question = "What did the dog do to the fox?"
# Tokenize the question
question_tokens = word_tokenize(question)
# Remove stopwords from the question
stopwords = set(stopwords.words('english'))
question_tokens = [word for word in question_tokens if word.lower() not in stopwords and word.isalpha()]
# Lemmatize the question tokens
lemmatizer = WordNetLemmatizer()
question_tokens = [lemmatizer.lemmatize(token) for token in question_tokens]
question_tokens = [x for x in question_tokens if '?' not in x]
# Find the sentence that contains the answer
answer = None
for sentence in sentences:
sentence_tokens = word_tokenize(sentence)
sentence_tokens = [word for word in sentence_tokens if word.lower() not in stopwords]
sentence_tokens = [lemmatizer.lemmatize(token) for token in sentence_tokens]
if set(question_tokens).issubset(set(sentence_tokens)):
answer = sentence
break
# Print the answer or a message if the answer cannot be found
if answer:
print(answer)
else:
print("Sorry, I couldn't find the answer to that question in the given passage.")
输出显示答案:
The quick brown fox jumps over the lazy dog.
此代码采用一段文本和一个问题,并尝试在段落中找到问题的答案。它将段落分词化为句子,并将问题分词化,删除停用词,并对分词进行词形还原。然后,它会搜索每个句子以查找与问题标记的匹配项,并打印包含答案的句子。
什么是信息提取
信息提取 (IE) 是从非结构化或半结构化数据源中自动提取结构化信息的过程。IE 通常涉及从文本数据中识别命名实体(例如,人员、地点、组织)以及它们之间的关系。
在 Python 中,一种流行的信息提取库是 spaCy。以下是使用 spaCy 从示例文本中提取命名实体的示例:
import spacy
nlp = spacy.load("en_core_web_sm")
text = "John Smith is a software engineer at Google in New York."
doc = nlp(text)
for ent in doc.ents:
print(ent.text, ent.label_)
John Smith PERSON
Google ORG
New York GPE
可视化输出。
from spacy import displacy
displacy.render(doc, style="ent", jupyter=True)
NLP 的未来
NLP 是一个快速发展的领域,仍有许多需要发现和改进的地方。随着机器学习算法变得越来越先进,NLP 有望变得更加准确和高效。NLP 也有望在教育、营销和客户服务等领域发挥越来越重要的作用。
更复杂的聊天机器人和虚拟助手的开发也有望推动 NLP 的增长。随着机器越来越擅长理解人类语言,它们将能够为用户提供更加个性化和有意义的交互。
Python 中的 NLP 项目示例
示例 1:标记化、POS 标记和情绪分析
import nltk
from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag
from nltk.sentiment import SentimentIntensityAnalyzer
text = "I am really excited about this new natural language processing project!"
tokens = word_tokenize(text)
pos_tags = pos_tag(tokens)
sentiment = SentimentIntensityAnalyzer().polarity_scores(text)
print("Tokens:", tokens)
print("POS tags:", pos_tags)
print("Sentiment:", sentiment)
输出:
Tokens: ['I', 'am', 'really', 'excited', 'about', 'this', 'new', 'natural', 'language', 'processing', 'project', '!']
POS tags: [('I', 'PRP'), ('am', 'VBP'), ('really', 'RB'), ('excited', 'VBN'), ('about', 'IN'), ('this', 'DT'), ('new', 'JJ'), ('natural', 'JJ'), ('language', 'NN'), ('processing', 'NN'), ('project', 'NN'), ('!', '.')]
Sentiment: {'neg': 0.0, 'neu': 0.593, 'pos': 0.407, 'compound': 0.6689}
示例 2:命名实体识别和文本分类
import nltk
from nltk.tokenize import word_tokenize
from nltk import pos_tag, ne_chunk
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('maxent_ne_chunker')
nltk.download('words')
text = "Steve Jobs was the CEO of Apple. Apple is located in California."
tokens = word_tokenize(text)
pos_tags = pos_tag(tokens)
named_entities = ne_chunk(pos_tags)
corpus = ["Steve Jobs was the CEO of Apple.", "Microsoft is located in Washington."]
labels = ["Apple", "Microsoft"]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)
clf = MultinomialNB().fit(X, labels)
classification = clf.predict(vectorizer.transform([text]))
print("Named entities:", named_entities)
print("Classification:", classification)
输出:
Named entities: (S
(PERSON Steve/NNP)
(PERSON Jobs/NNP)
was/VBD
the/DT
(ORGANIZATION CEO/NNP)
of/IN
(GPE Apple/NNP)
./.
(PERSON Apple/NNP)
is/VBZ
located/VBN
in/IN
(GPE California/NNP)
./.)
Classification: ['Apple']
用于自然语言处理 (NLP) 的有用 Python 库
- 使用 nltk 的 NLP:word_tokenize、pos_tag、ne_chunk、sent_tokenize、wordnet、NaiveBayesClassifier、DecisionTreeClassifier
- 具有空间的 NLP:load、tokenizer、tagger、parser、ner、displacy
- 使用 gensim 的 NLP:语料库。字典、模型。Word2Vec,模型。Lda模型
- 带有 textblob 的 NLP:TextBlob、Word、Blobber、Sentiment、TextBlobDE、TextBlobFR
- 使用 scikit-learn 的 NLP:CountVectorizer、TfidfVectorizer、SVC、KNeighborsClassifier、RandomForestClassifier
常见问题解答
什么是 NLP?
分析、理解和生成人类语言。
NLP 有哪些应用?
情感分析、聊天机器人、机器翻译、语音识别等。
NLP 面临哪些挑战?
歧义、上下文、成语、俚语等。
NLP 中常用的技术有哪些?
令牌化、POS 标记、解析、信息提取等。
什么是 NLP 中的深度学习?
基于神经网络的文本分类、机器翻译等模型。
有哪些流行的 NLP 库?
NLTK、spaCy、Gensim、Transformers 等。