Press "Enter" to skip to content

揭秘自然语言处理:自然语言处理基础和技术初学者指南

由Jr Korpa在Unsplash上的照片

自然语言处理(NLP)是机器学习中令人兴奋的领域,它使机器能够理解、解释、理解和生成人类语言。它基本上是允许计算机阅读、理解和响应人类语言的技术,无论是以文本还是语音的形式。就像教机器说我们的语言,甚至生成创造性、连贯和上下文相关的回答一样。在本文中,我们将深入探讨ChatGPT和当今众多生成式AI系统的基本术语、术语和基础知识。

关键术语包括:

文档

一段文字,可以是一个句子,也可以是一本书。

语料库

用于NLP分析或训练的文档集合。

corpus = ["这是第一个文档。", "这里还有另一个文档。", "还有第三个文档。"]

词汇表

语料库中所有唯一单词的集合。

from collections import Countercorpus = ["这是第一个文档。", "这里还有另一个文档。", "还有第三个文档。"]words = ' '.join(corpus).lower().split()vocabulary = set(words)print("词汇表:", vocabulary)

词汇表: {'文档。', '文档', '第一个', '一个', '另一个', '和', '第三个', '这', '这里。', '是', '了', '还有'}

分割

将文本分割成有意义的片段,如句子或段落的过程。

标记化

将文本分割成较小的单元,如单词或子词(标记)。

from nltk.tokenize import word_tokenizetext = "标记化是NLP中的一个重要步骤。"tokens = word_tokenize(text)print("标记:", tokens)

标记: ['标记化', '是', '一个', '重要', '步骤', '在', 'NLP', '.']

停用词

通常在NLP分析中被删除的常用词(例如’和’,’the’,’is’)。

from nltk.corpus import stopwordsstop_words = set(stopwords.words('english'))print("停用词:", stop_words)

停用词: {'he', 'once', 'm', 'this', "that'll", 'their', 'the', "she's", "you've", "hadn't", 'mightn', 'down', 'off', 'now', "shouldn't", 't', "isn't", 'that', "didn't", 'wasn', 'do', 'shan', 'yourselves', 'a', 've', 'themselves', 'out', "don't", 'hasn', 'than', 'couldn', "mightn't", "you'd", 'further', 'has', 'having', "wouldn't", 'here', 'him', 'from', 'where', 'your', 'these', 'my', 'up', 'so', 'have', 'hadn', "weren't", 'to', 'hers', 'doesn', 'below', "needn't", 're', "you're", 'when', 'whom', 'all', 'is', 'should', 'not', 'were', 'you', 'until', 'doing', "mustn't", "it's", 'because', 'y', 'her', 'both', 'o', 'weren', 'other', 'on', 'his', "shan't", 'why', 'through', 'between', 'am', 'be', 'she', 'more', 'herself', "couldn't", "doesn't", "aren't", 'which', 'won', 'of', 'don', 'some', 'was', 'under', 'few', 'needn', 'ours', 'theirs', 'it', 'aren', 'and', 'own', 'isn', 'about', 'such', 'again', 'its', 'any', 'by', 'mustn', 'had', 's', 'can', 'haven', 'before', 'over', 'those', 'during', 'while', "wasn't", 'we', 'each', 'being', 'then', 'against', 'me', "should've", 'd', 'after', 'didn', 'as', 'll', "haven't", 'wouldn', 'there', 'an', 'been', 'ourselves', "you'll", 'what', 'if', 'in', 'shouldn', 'for', 'with', 'just', 'how', 'who', 'them', 'are', 'but', 'no', 'ain', 'very', 'ma', 'same', 'above', 'into', 'himself', 'did', 'myself', 'most', 'only', 'will', 'our', 'they', 'nor', 'yours', 'at', 'too', "hasn't", 'itself', 'or', "won't", 'does', 'i', 'yourself'}

词干提取

将单词缩减为其基本形式或根形式(词干)。

from nltk.stem import PorterStemmerstemmer = PorterStemmer()word = "running"stemmed_word = stemmer.stem(word)print("词干提取后的单词:", stemmed_word)

词干提取后的单词: run

词形归并

将单词缩减为其基本形式(词元),考虑上下文。

from nltk.stem import WordNetLemmatizerlemmatizer = WordNetLemmatizer()word = "Raqib喜欢编码和跳舞。"lemmatized_word = lemmatizer.lemmatize(word)print("词形归并后的单词:", lemmatized_word)

词性标注

为句子中的每个单词分配一个词性(例如名词、动词、形容词)。

from nltk import pos_tagfrom nltk.tokenize import word_tokenizesentence = "The cat is on the mat"tokens = word_tokenize(sentence)pos_tags = pos_tag(tokens)print("词性标注结果:", pos_tags)

词性标注结果: [('The', 'DT'), ('cat', 'NN'), ('is', 'VBZ'), ('on', 'IN'), ('the', 'DT'), ('mat', 'NN')]
  • ('The', 'DT'): ‘The’ 是一个限定词(DT)。
  • ('cat', 'NN'): ‘cat’ 是一个名词(NN)。
  • ('is', 'VBZ'): ‘is’ 是一个动词,第三人称单数现在时(VBZ)。
  • ('on', 'IN'): ‘on’ 是一个介词或从属连词(IN)。
  • ('the', 'DT'): ‘the’ 是一个限定词(DT)。
  • ('mat', 'NN'): ‘mat’ 是一个名词(NN)。

词袋模型(BoW)

文本的一种表示形式,计算文档中单词的频率,忽略语法和词序。

from sklearn.feature_extraction.text import CountVectorizercorpus = ["这是第一个文档。", "这里是另一个文档。", "这是第三个文档。"]vectorizer = CountVectorizer()bow_representation = vectorizer.fit_transform(corpus)print("词袋模型表示:\n", bow_representation.toarray())print("词汇表:", vectorizer.get_feature_names())

TF-IDF(词频-逆文档频率)

一种根据频率相对于语料库衡量文档中单词重要性的技术。

from sklearn.feature_extraction.text import TfidfVectorizercorpus = ["这是第一个文档。", "这里是另一个文档。", "这是第三个文档。"]vectorizer = TfidfVectorizer()tfidf_representation = vectorizer.fit_transform(corpus)print("TF-IDF表示:\n", tfidf_representation.toarray())print("词汇表:", vectorizer.get_feature_names())

TF-IDF表示: [[0.         0.         0.35543247 0.46735098 0.         0.46735098  0.         0.46735098 0.         0.46735098] [0.         0.62276601 0.4736296  0.         0.62276601 0.  0.         0.         0.         0.        ] [0.57735027 0.         0.         0.         0.         0.  0.57735027 0.         0.57735027 0.        ]]词汇表: ['and', 'another', 'document', 'first', 'here', 'is', 'one', 'the', 'third', 'this']

文本预处理步骤

现在,我们将应用基本的自然语言处理技术对文本字符串进行预处理。

将文本转换为小写。

sample_text = "NLP是一个令人兴奋的领域!它使机器能够理解、解释和生成人类语言。了解更多信息,请访问 https://raqibcodes.com. #NLP #MachineLearning @NLPCommunity 2023303"# 将文本转换为小写def convert_to_lowercase(text):    return text.lower()# 应用小写转换lowercased_text = convert_to_lowercase(sample_text)print("小写转换后的文本:", lowercased_text)

小写转换后的文本: nlp是一个令人兴奋的领域!它使机器能够理解、解释和生成人类语言。了解更多信息,请访问 https://raqibcodes.com. #nlp #machinelearning @nlpcommunity 2023303

去除特殊字符。

def remove_special_characters(text):    # 去除URL、hashtags、mentions和特殊字符    text = re.sub(r"http\S+|www\S+|@\w+|#\w+", "", text)    text = re.sub(r"[^\w\s.]", "", text)    return text# 应用去除特殊字符text_no_special_chars = remove_special_characters(lowercased_text)print("去除特殊字符后的文本:", text_no_special_chars)

去除特殊字符后的文本: nlp是一个令人兴奋的领域,它使机器能够理解、解释和生成人类语言。了解更多信息请访问2023303

去除数字和数字。

def remove_numbers(text):    # 去除数字/数字    text = re.sub(r'\d+(\.\d+)?', '', text)    return text# 应用去除数字/数字text_no_numbers = remove_numbers(text_no_special_chars)print("去除数字/数字后的文本:", text_no_numbers)

去除数字/数字后的文本: nlp是一个令人兴奋的领域,它使机器能够理解、解释和生成人类语言。了解更多信息请访问

分词。

from nltk.tokenize import word_tokenizedef tokenize_text(text):    # 分词    tokens = word_tokenize(text)    return tokens# 应用分词tokens = tokenize_text(text_no_numbers)print("分词结果:", tokens)

分词结果: ['nlp', 'is', 'an', 'exciting', 'field', 'it', 'enables', 'machines', 'to', 'comprehend', 'interpret', 'and', 'generate', 'human', 'language', '.', 'learn', 'more', 'at']

去除停用词。

from nltk.corpus import stopwordsdef remove_stopwords(tokens):    # 去除停用词    stop_words = set(stopwords.words('english'))    tokens = [token for token in tokens if token not in stop_words]    return tokens# 应用去除停用词tokens_no_stopwords = remove_stopwords(tokens)print("去除停用词后的分词结果:", tokens_no_stopwords)

去除停用词后的分词结果: ['nlp', 'exciting', 'field', 'enables', 'machines', 'comprehend', 'interpret', 'generate', 'human', 'language', '.', 'learn']

词形还原。

from nltk.stem import WordNetLemmatizerdef lemmatize_words(tokens):    # 词形还原    lemmatizer = WordNetLemmatizer()    tokens = [lemmatizer.lemmatize(token) for token in tokens]    return tokens# 应用词形还原lemmatized_tokens = lemmatize_words(tokens_no_stopwords)print("词形还原后的分词结果:", lemmatized_tokens)

词形还原后的分词结果: ['nlp', 'exciting', 'field', 'enables', 'machine', 'comprehend', 'interpret', 'generate', 'human', 'language', '.', 'learn']

应用词干化。

from nltk.stem import PorterStemmerdef apply_stemming(tokens):    # 应用词干化    stemmer = PorterStemmer()    stemmed_tokens = [stemmer.stem(token) for token in tokens]    return stemmed_tokens# 应用词干化stemmed_tokens = apply_stemming(lemmatized_tokens)print("词干化后的分词结果:", stemmed_tokens)

词干化后的分词结果: ['nlp', 'excit', 'field', 'enabl', 'machin', 'comprehend', 'interpret', 'gener', 'human', 'languag', '.', 'learn']

将分词重新合并成一个字符串。

def join_tokens(tokens):    # 将分词重新合并成一个字符串    return ' '.join(tokens)# 应用将分词合并成一个字符串preprocessed_text = join_tokens(lemmatized_tokens)print("预处理后的文本:", preprocessed_text)

预处理后的文本: nlp 令人兴奋 领域 使 机器 能够 理解 解释 生成 人类 语言 . learn

应用词性标注。

from nltk import pos_tagdef pos_tagging(tokens):    # 执行词性标注    pos_tags = pos_tag(tokens)    return pos_tags# 应用词性标注pos_tags = pos_tagging(lemmatized_tokens)print("词性标注结果:", pos_tags)

词性标注结果: [('nlp', 'RB'), ('exciting', 'JJ'), ('field', 'NN'), ('enables', 'NNS'), ('machine', 'NN'), ('comprehend', 'VBP'), ('interpret', 'JJ'), ('generate', 'NN'), ('human', 'JJ'), ('language', 'NN'), ('.', '.'), ('learn', 'VB')]

标签的含义

  • ('nlp', 'RB'): ‘nlp’ 被标记为副词 (RB)。
  • ('exciting', 'JJ'): ‘exciting’ 是形容词 (JJ)。
  • ('field', 'NN'): ‘field’ 是名词 (NN)。
  • ('enables', 'NNS'): ‘enables’ 是复数名词 (NNS)。
  • ('machine', 'NN'): ‘machine’ 是名词 (NN)。
  • ('comprehend', 'VBP'): ‘comprehend’ 是动词原形 (VBP)。
  • ('interpret', 'JJ'): ‘interpret’ 是形容词 (JJ)。
  • ('generate', 'NN'): ‘generate’ 是名词 (NN)。
  • ('human', 'JJ'): ‘human’ 是形容词 (JJ)。
  • ('language', 'NN'): ‘language’ 是名词 (NN)。
  • ('.', '.'): ‘.’ 表示标点符号 (句号)。
  • ('learn', 'VB'): ‘learn’ 是动词原形 (VB)。

应用词袋模型表示。

from sklearn.feature_extraction.text import CountVectorizerdef bag_of_words_representation(text):    # 初始化CountVectorizer    vectorizer = CountVectorizer()    # 将文本转换为词袋模型表示    bag_of_words_representation = vectorizer.fit_transform([text])    return bag_of_words_representation, vectorizer# 应用词袋模型表示bag_of_words_representation, vectorizer = bag_of_words_representation(preprocessed_text)print("词袋模型表示:")print(bag_of_words_representation.toarray())print("词汇表:", vectorizer.get_feature_names())

词袋模型表示:[[1 1 1 1 1 1 1 1 1 1 1]]词汇表: ['comprehend', 'enables', 'exciting', 'field', 'generate', 'human', 'interpret', 'language', 'learn', 'machine', 'nlp']

应用TF-IDF表示。

from sklearn.feature_extraction.text import TfidfVectorizerdef tfidf_representation(text):    # 初始化TfidfVectorizer    vectorizer = TfidfVectorizer()    # 将文本转换为TF-IDF表示    tfidf_representation = vectorizer.fit_transform([text])    return tfidf_representation, vectorizer# 应用TF-IDF表示tfidf_representation, tfidf_vectorizer = tfidf_representation(preprocessed_text)print("\nTF-IDF表示:")print(tfidf_representation.toarray())print("词汇表:", tfidf_vectorizer.get_feature_names())

TF-IDF表示:[[0.30151134 0.30151134 0.30151134 0.30151134 0.30151134 0.30151134  0.30151134 0.30151134 0.30151134 0.30151134 0.30151134]]词汇表: ['comprehend', 'enables', 'exciting', 'field', 'generate', 'human', 'interpret', 'language', 'learn', 'machine', 'nlp']

自然语言处理 (NLP) 是连接人类语言与机器之间的桥梁。在本文中,我们揭示了诸如 ‘corpus’、’vocabulary’ 之类的基本术语,以及 ‘tokenization’、’lemmatization’ 和 ‘POS tagging’ 等关键技术。这些是构建高级 NLP 应用的基石,将人工智能推向更具人类化的交互。

感谢阅读🤓。您可以查看我的 GitHub 存储库,您可以在那里审查一个我参与的 NLP 项目,我在其中应用了以上所有技术和更高级的技术。干杯!

Leave a Reply

Your email address will not be published. Required fields are marked *