【NLP-02】文本表达---词袋模型、TF-IDF、Word2Vec、Doc2Vec、FastText和Universal Sentence Encoder模型

NLP的向量表达一般包含以下一些种类:

  • 词袋模型:简单易实现,适用于文本分类等任务。但是由于忽略了单词的顺序和语义关系,所以在处理长文本或需要考虑单词含义的任务(如机器翻译)时可能效果不佳。
  • TF-IDF模型:相比词袋模型更能反映单词在文章中的重要性,通常用于文本分类、信息检索等任务。但是该方法仍然忽略了单词之间语义关系,且对于罕见单词缺乏泛化能力。
  • Word2Vec模型:通过学习单词之间的语义关系生成词向量,在自然语言处理任务中应用广泛,如文本分类、词义消歧、信息检索等。但是该方法对于生僻词或低频词的表现不佳,且不能直接捕捉句子级别的语义信息。
  • Doc2Vec模型:通过学习整个文档的嵌入来表示文档,通常用于文档分类、推荐系统等任务。但是该方法需要足够的训练数据,且模型复杂度较高。
  • FastText模型:相比Word2Vec模型加入了单词子串信息,可以处理罕见单词和未登录词。适用于文本分类、词义消歧等任务。但是由于增加了子串信息,模型大小和计算量都会增加。
  • Universal Sentence Encoder模型:适用于生成句向量,可用于文本分类、情感分析、问答系统、推荐系统等任务。该模型具有多语言支持和迁移学习能力,在跨语言和少样本场景下效果优秀,但是模型较大,计算量较大。(预训练模型BERT,ERNIE,ChatGPT等)
    需要根据具体任务的特点和数据集的特征选择合适的方法并进行调参优化,以获得最好的效果。

一、词袋模型

该方法假设文本中词汇的出现顺序并不重要,而只关注词汇的频率。因此,可以将每个单词看作独立的特征,并构建一个基于词频的向量来表示整个文档。

在Python中,可以使用sklearn库的CountVectorizer类实现词袋模型:

from sklearn.feature_extraction.text import CountVectorizer

定义一组文本

corpus= ['This is the first document.',
         'This is the second document.',
         'This is the third document.']

构建词袋模型

vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)
print(X.toarray())

注:当然词袋模型模型也分多中类型,如是否包含出现的次数?等等

二、TF-IDF模型

与词袋模型相比,TF-IDF模型考虑了单词在整个语料库中的稀缺性,以及在特定文档中的频率。因此,它可以更好地反映单词在文档中的重要性。

在Python中,可以使用sklearn库的TfidfVectorizer类实现TF-IDF模型:具体的参考TF-IDF算法介绍.md

from sklearn.feature_extraction.text import TfidfVectorizer

定义一组文本

corpus = ['This is the first document.',
          'This is the second document.',
          'This is the third document.']

构建TF-IDF模型

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)
print(X.toarray())

三、Word2Vec模型

该模型通过学习单词之间的语义关系来生成词向量。具体来说,Word2Vec模型分为两种训练方式:CBOW(Continuous Bag-of-Words)和Skip-gram。

在Python中,可以使用gensim库实现Word2Vec模型:

from gensim.models import Word2Vec

定义一组句子

sentences = [['this', 'is', 'the', 'first', 'sentence', '.'],
             ['this', 'is', 'the', 'second', 'sentence', '.'],
             ['this', 'is', 'the', 'third', 'sentence', '.']]

训练Word2Vec模型 词向量

model = Word2Vec(sentences, min_count=1, size=5)
print(model.wv['sentence'])

将词向量变成句向量的

Word2Vec模型可以通过两种方式来生成句向量:

平均池化(Average Pooling):将句子中所有单词的词向量求平均值作为句向量表示。这种方法简单易用,但是可能会忽略单词之间的顺序关系和语义信息。
加权平均池化(Weighted Average Pooling):根据每个单词在句子中的重要性给它们的词向量赋予不同的权重,并将加权后的词向量进行平均池化。这种方法可以更好地反映句子中单词的重要性和顺序关系,因此通常效果更好。
下面是一个使用Word2Vec模型生成句向量的示例代码:

from gensim.models import Word2Vec

定义一组句子

sentences = [['this', 'is', 'the', 'first', 'sentence', '.'],
             ['this', 'is', 'the', 'second', 'sentence', '.'],
             ['this', 'is', 'the', 'third', 'sentence', '.']]

训练Word2Vec模型

model = Word2Vec(sentences, size=5, window=2, min_count=1, workers=4, sg=1)

平均池化

avg_vector = sum([model.wv[word] for word in sentence]) / len(sentence)
print(avg_vector)

加权平均池化

weighted_vectors = [(model.wv[word], 0.5) for word in sentence]
weighted_avg_vector = sum([vector * weight for vector, weight in weighted_vectors]) / sum([weight for _, weight in weighted_vectors])
print(weighted_avg_vector)

四、Doc2Vec模型

该模型对文档进行建模,将整个文档表示为一个向量。与Word2Vec模型类似,Doc2Vec模型也分为两种训练方式:PV-DM(distributed memory model of paragraph vectors)和PV-DBOW(distributed bag of words version of paragraph vectors)。

在Python中,可以使用gensim库实现Doc2Vec模型:

from gensim.models.doc2vec import Doc2Vec, TaggedDocument

定义一组文档

documents = [TaggedDocument(doc, [i]) for i, doc in enumerate(
['This is the first document.',
'This is the second document.',
'This is the third document.'])]

训练Doc2Vec模型

model = Doc2Vec(documents, vector_size=5, window=2, min_count=1, workers=4, epochs=100)
print(model.docvecs[0])

五、FastText模型

该模型是对Word2Vec模型的扩展,可以处理单词中的子词信息。具体来说,FastText模型将每个单词表示为其所有可能的子串的平均值,并使用这些子串的向量来生成单词向量。

在python中,可以使用gensim库实现FastText模型:

from gensim.models.fasttext import FastText

定义一组句子

sentences = [['this', 'is', 'the', 'first', 'sentence', '.'],
             ['this', 'is', 'the', 'second', 'sentence', '.'],
             ['this', 'is', 'the', 'third', 'sentence', '.']]

训练FastText模型

model = FastText(sentences, size=5, window=2, min_count=1, workers=4, sg=1)
print(model.wv['sentence'])

注:也可以使用FastText模型实现文本分类;

from gensim.models import FastText
from gensim.test.utils import common_texts, get_tmpfile

训练FastText模型

model = FastText(common_texts, size=4, window=3, min_count=1, iter=10)

对测试集进行预测

test_data = ['this is a positive sentence', 'this is a negative sentence']
for text in test_data:
    predicted_label = model.wv.most_similar(text)[0][0]
    print('predicted label:', predicted_label)

六、Universal Sentence Encoder模型

该模型是由Google提出的一种用于生成句向量的神经网络模型。它使用Transformer架构来对输入句子进行编码,并生成一个512维的向量表示。

在Python中,可以使用TensorFlow Hub库调用Universal Sentence Encoder模型:

import tensorflow_hub as hub
import tensorflow_text

加载Universal Sentence Encoder模型

module_url = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3"
model = hub.load(module_url)

生成句向量

sentences = ["This is the first sentence.", "This is the second sentence.", "This is the third sentence."]
embeddings = model(sentences)
print(embeddings)

其他大模型的编码方式流程和上面代码过程相似,导入模型—实现编码;大模型的来源可以是huggingface、paddlepaddle、Openai等等;

  • 26
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云天徽上

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值