Keras NLP——词嵌入模型

一.词嵌入概念

词嵌入是一种提供单词的密集向量表示的方法,可以捕获单词的含义。词嵌入是对简单的词袋模型编码方案的改进,任何一个文档在词袋模型方案的编码下最终形成的是一个巨大的稀疏的向量(大多数是0值),仅仅捕获的是文档的内容,而不是词的意思。词嵌入模型是在大规模文本语料库上通过使用一定的算法训练一组固定长度密集和连续值向量获得的。每个单词由嵌入空间中的一个点表示,这些点是根据围绕目标单词的单词学习和移动的。词本身由自己的伴生词(文本中词两侧的词)来定义的,可以通过嵌入来学习单词的意思。单词向量空间表示提供了一个投影,其中具有相似含义的单词在空间内局部聚类。关于词嵌入的具体细节请参考本篇博客:迁移学习的概念与方法

二.开发Word2Vec嵌入

Word2Vec是一种用于从文本语料库中学习词嵌入模型的算法。有两种主要的训练算法可用于从文本学习词嵌入模型:连续词袋(CBOW)和Skip-Gram。Word2Vec模型训练需要大量文本,例如整个维基百科语料库。在此,仅仅使用一个小文本例子来演示训练词嵌入模型的原理。Gensim Python包提供了使用Word2Vec模型的Word2Vec类。从文本学习单词嵌入模型涉及到文本加载、将文本分割成句子并将它作为参数传递给Word2Vec实例的构造函数。具体而言,每个句子必须被标记化,意味着分成单词并准备好。句子可以是加载到内存中的文本,也可以是逐步加载文本的迭代器(大规模文本语料库加载方法)。Gensim Word2Vec构造函数有很多参数,下面是一些值得注意的参数:

  • size:(默认值100)词嵌入向量的维数
  • window:(默认值5) 目标词与目标词周围词之间的最大距离
  • min count:(默认值5) 训练模型时需要考虑的最小字数,小于此计数的单词将被忽略
  • workers:(默认值3) 训练时使用的线程数
  • sg:(默认值0) 训练算法:0表示CBOW,1表示Skip-Gram
    在模型训练之后,可以通过wv属性访问它。还能通过调用单词矢量模型上的save_word2vec_format()函数将训练好的模型文件保存到文件中(默认情况下,模型以二进制格式保存以节省空间)。然后还可以通过调用Word2Vec.load()函数再次加载保存的模型。
#!/usr/bin/env python3
# encoding: utf-8
'''
@file: Keras_word2vec.py
@time: 2020/7/5 0005 21:59
@author: Jack
@contact: jack18588951684@163.com
'''

from gensim.models import Word2Vec

sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],
             ['this', 'is', 'the', 'second', 'sentence'],
             ['yet', 'another', 'sentence'],
             ['one', 'more', 'sentence'],
             ['and', 'the', 'final', 'sentence']]

model = Word2Vec(sentences, min_count=1)
print(model)
words = list(model.wv.vocab)
print(words)
print(model['sentence'])
model.save('model.bin')
new_model = Word2Vec.load('model.bin')
print(new_model)

Word2Vec(vocab=14, size=100, alpha=0.025)
['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec', 'second', 'yet', 'another', 'one', 'more', 'and', 'final']
[ 1.5970342e-03  3.0990422e-03 -1.5597004e-03  1.0130922e-04
  4.6453704e-03  4.8387623e-03 -1.7510486e-03 -1.3356048e-03
 -1.9883395e-03  5.9007361e-05 -1.1112307e-03 -4.1536316e-03
  3.6945145e-03 -1.6147217e-03  2.7425054e-03 -3.7472381e-03
 -2.8020672e-03  4.3358863e-03  1.1823174e-03  2.9089549e-03
  3.3314351e-03 -6.5788359e-04  6.9831114e-04  4.0198332e-03
 -3.8785536e-03  3.6612628e-03 -3.7423281e-03 -6.5154553e-04
  1.1573763e-03  2.1937855e-04  1.5912919e-03  8.7182119e-04
 -3.2798641e-03  3.1347673e-03 -2.3850927e-03  4.3258183e-03
 -1.9930664e-03 -3.8760060e-03 -8.6675974e-04  2.8453881e-04
 -1.7244455e-03 -4.9040834e-03 -4.0097716e-03 -4.2938511e-03
  1.0308551e-03  7.8650279e-04  5.0712365e-04  3.5261957e-03
  4.0291143e-03 -2.9941991e-03  2.8647142e-03  1.5664878e-03
  4.4487659e-03  3.3967711e-03  4.8973183e-03 -2.1807828e-03
  2.0259018e-03  1.8970913e-03 -2.1978706e-04 -8.5533579e-04
  2.9131054e-04 -3.3934473e-03 -1.1175221e-03  4.6166801e-03
 -2.0422529e-04  3.1610699e-03  4.8198495e-03  1.6930439e-05
  5.3703779e-04 -4.9693636e-03  2.5525053e-03 -4.3471768e-03
  2.9601078e-03  4.3827929e-03 -3.4209811e-03  3.5368798e-03
  4.8480975e-03 -1.5721031e-03  2.2279820e-03  2.1352980e-03
  4.7594612e-04 -9.6263684e-04 -2.1694885e-03  2.5529866e-03
 -1.8718592e-03  1.5937366e-03 -2.8575391e-03  3.5459616e-03
  3.1409469e-03  3.9983247e-03  2.3655379e-03  2.7748533e-03
 -4.7552404e-03  9.8598364e-04 -4.1911597e-03 -5.8383367e-04
  4.7576688e-03  2.0652534e-03  4.6017808e-03  1.8423117e-03]
Word2Vec(vocab=14, size=100, alpha=0.025)

三.可视化词嵌入

在矢量上使用投影方法将其降维,例如scikit-learn中提供的那些方法,然后使用Matplotlib将投影绘制为散点图来可视化词嵌入。

#!/usr/bin/env python3
# encoding: utf-8
'''
@file: Keras_word2vec.py
@time: 2020/7/5 0005 21:59
@author: Jack
@contact: jack18588951684@163.com
'''

from gensim.models import Word2Vec
from sklearn.decomposition import PCA
from matplotlib import pyplot

sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],
             ['this', 'is', 'the', 'second', 'sentence'],
             ['yet', 'another', 'sentence'],
             ['one', 'more', 'sentence'],
             ['and', 'the', 'final', 'sentence']]

model = Word2Vec(sentences, min_count=1)
print(model)
words = list(model.wv.vocab)
print(words)
print(model['sentence'])
model.save('model.bin')
new_model = Word2Vec.load('model.bin')
print(new_model)
X = model[model.wv.vocab]
pca = PCA(n_components=2)
result = pca.fit_transform(X)
pyplot.scatter(result[:, 0], result[:, 1])
for i, word in enumerate(words):
    pyplot.annotate(word, xy=(result[i, 0], result[i, 1]))
pyplot.show()

在这里插入图片描述

四.词嵌入预训练模型

训练自己的单词向量可能是给定NLP问题的最佳方法。但是它可能不但需要很长时间,还需要海量的数据以及对训练算法方面的一些专业知识也有要求。另一种方法就是简单地使用现有的预训练单词嵌入模型。Google的Word2Vec模型时在其新闻数据(约1000亿字)上训练得到的;它包含300多万个单词和短语,词向量是300维的,这是一个1.53GB的文件,下载链接为:Word2Vec预训练模型 ,模型下载好之后,可以通过Gensim库的KeyedVectors.load_word2vec_format()函数将此模型加载到内存中,然后通过一个有趣的例子来测试下是否载入成功:

from gensim.models import KeyedVectors

filename = r'F:\工作资料\NLP\词嵌入模型\Word2Vec\GoogleNews-vectors-negative300.bin'
model = KeyedVectors.load_word2vec_format(filename, binary=True)
result = model.most_similar(positive=['woman', 'king'], negative=['man'], topn=1)
print(result)
[('queen', 0.7118192315101624)]

此外,斯坦福大学的研究人员也开发了一套像Word2Vec一样的词嵌入模型训练算法,称为全局向量词表示(Global Vector for Word Representation)法,简称Glove(NLP从业者似乎更喜欢Glove)。与Word2Vec一样,Glove研究人员也提供预训练的单词向量,可供选择。下载Glove预训练模型后,第一步是通过Gensim的glove2word2vec()函数将Glove文件格式转换为Word2Vec文件格式。Glove预训练模型下载链接为:Glove预训练模型

from gensim.models import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec
glove_input_file = 'glove/glove.6B.100d.txt'
word2vec_output_file = 'glove.6B.100d.txt.word2vec'
glove2word2vec(glove_input_file ,word2vec_output_file )
filename = 'glove.6B.100d.txt.word2vec'
model = KeyedVectors.load_word2vec_format(filename,binary=False)
result = model.most_similar(positive=['woman','king'],negative=['man'],topn=1)
print(result)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用Keras构建情感分析模型的代码示例: 首先,需要导入需要的库: ```python import pandas as pd import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Embedding, Conv1D, GlobalMaxPooling1D, Dense ``` 接着,读取数据集并进行预处理: ```python # 读取数据集 data = pd.read_csv('sentiment_analysis.csv') # 将文本转换为小写 texts = data['text'].apply(lambda x: x.lower()) # 将标签转换为数字:0表示负面情感,1表示正面情感 labels = np.array([0 if label == 'negative' else 1 for label in data['label']]) ``` 然后,进行单词向量化: ```python # 将文本转换为单词序列 tokenizer = Tokenizer(num_words=5000) tokenizer.fit_on_texts(texts) sequences = tokenizer.texts_to_sequences(texts) # 对单词序列进行填充,使其长度相同 padded_sequences = pad_sequences(sequences, maxlen=100) ``` 接下来,构建模型: ```python model = Sequential() # 添加嵌入层 model.add(Embedding(input_dim=5000, output_dim=100, input_length=100)) # 添加1D卷积层 model.add(Conv1D(filters=32, kernel_size=3, padding='same', activation='relu')) # 添加全局最大池化层 model.add(GlobalMaxPooling1D()) # 添加全连接层 model.add(Dense(units=64, activation='relu')) # 添加输出层 model.add(Dense(units=1, activation='sigmoid')) # 编译模型 model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) ``` 最后,训练模型并进行评估: ```python # 划分训练集和测试集 indices = np.arange(padded_sequences.shape[0]) np.random.shuffle(indices) padded_sequences = padded_sequences[indices] labels = labels[indices] train_size = int(0.8 * padded_sequences.shape[0]) train_X, test_X = padded_sequences[:train_size], padded_sequences[train_size:] train_y, test_y = labels[:train_size], labels[train_size:] # 训练模型 model.fit(train_X, train_y, epochs=10, batch_size=64) # 评估模型 loss, accuracy = model.evaluate(test_X, test_y) print('Test accuracy:', accuracy) ``` 完整的代码示例如下: ```python import pandas as pd import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Embedding, Conv1D, GlobalMaxPooling1D, Dense # 读取数据集 data = pd.read_csv('sentiment_analysis.csv') # 将文本转换为小写 texts = data['text'].apply(lambda x: x.lower()) # 将标签转换为数字:0表示负面情感,1表示正面情感 labels = np.array([0 if label == 'negative' else 1 for label in data['label']]) # 将文本转换为单词序列 tokenizer = Tokenizer(num_words=5000) tokenizer.fit_on_texts(texts) sequences = tokenizer.texts_to_sequences(texts) # 对单词序列进行填充,使其长度相同 padded_sequences = pad_sequences(sequences, maxlen=100) # 构建模型 model = Sequential() # 添加嵌入层 model.add(Embedding(input_dim=5000, output_dim=100, input_length=100)) # 添加1D卷积层 model.add(Conv1D(filters=32, kernel_size=3, padding='same', activation='relu')) # 添加全局最大池化层 model.add(GlobalMaxPooling1D()) # 添加全连接层 model.add(Dense(units=64, activation='relu')) # 添加输出层 model.add(Dense(units=1, activation='sigmoid')) # 编译模型 model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # 划分训练集和测试集 indices = np.arange(padded_sequences.shape[0]) np.random.shuffle(indices) padded_sequences = padded_sequences[indices] labels = labels[indices] train_size = int(0.8 * padded_sequences.shape[0]) train_X, test_X = padded_sequences[:train_size], padded_sequences[train_size:] train_y, test_y = labels[:train_size], labels[train_size:] # 训练模型 model.fit(train_X, train_y, epochs=10, batch_size=64) # 评估模型 loss, accuracy = model.evaluate(test_X, test_y) print('Test accuracy:', accuracy) ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值