我想在训练,验证和推理阶段使用TensorFlow Transform将标记转换为单词向量.
我按照这个StackOverflow帖子实现了从标记到向量的初始转换.转换按预期工作,我获取EMB_DIM每个令牌的向量.
import numpy as np
import tensorflow as tf
tf.reset_default_graph()
EMB_DIM = 10
def load_pretrained_glove():
tokens = ["a", "cat", "plays", "piano"]
return tokens, np.random.rand(len(tokens), EMB_DIM)
# sample string
string_tensor = tf.constant(["plays", "piano", "unknown_token", "another_unknown_token"])
pretrained_vocab, pretrained_embs = load_pretrained_glove()
vocab_lookup = tf.contrib.lookup.index_table_from_tensor(
mapping = tf.constant(pretrained_vocab),
default_value = len(pretrained_vocab))
string_tensor = vocab_lookup.lookup(string_tensor)
# define the word embedding
pretrained_embs = tf.get_variable(
name="embs_pretrained",
initializer=tf.constant_initializer(np.asarray(pretrained_embs), dtype=tf.float32),
shape=pretrained_embs.shape,
trainable=False)
unk_embedding = tf.get_variable(
name="unk_embedding",
shape=[1, EMB_DIM],
initializer=tf.random_uniform_initializer(-0.04, 0.04),
trainable=False)
embeddings = …Run Code Online (Sandbox Code Playgroud) 我在https://nlp.stanford.edu/projects/glove/下载的手套矢量文件gloves.6B.50d.txt中找到了"unk"令牌.其价值如下:
unk -0.79149 0.86617 0.11998 0.00092287 0.2776 -0.49185 0.50195 0.00060792 -0.25845 0.17865 0.2535 0.76572 0.50664 0.4025 -0.0021388 -0.28397 -0.50324 0.30449 0.51779 0.01509 -0.35031 -1.1278 0.33253 -0.3525 0.041326 1.0863 0.03391 0.33564 0.49745 -0.070131 -1.2192 -0.48512 -0.038512 -0.13554 -0.1638 0.52321 -0.31318 -0.1655 0.11909 -0.15115 -0.15621 -0.62655 -0.62336 -0.4215 0.41873 -0.92472 1.1049 -0.29996 -0.0063003 0.3954
Run Code Online (Sandbox Code Playgroud)
它是用于未知单词的标记还是某种缩写?
我试着遵循这个.
但是有些我浪费了很多时间而没有任何用处.
我只想GloVe在我自己的语料库(~900Mb corpus.txt文件)上训练模型.我下载了上面链接中提供的文件并使用它编译cygwin(在编辑demo.sh文件并将其更改为VOCAB_FILE=corpus.txt.我应该CORPUS=text8保持不变吗?)输出为:
我怎样才能将这些文件作为GloVe模型加载到python上?
word2vec 和手套有什么区别?这两种方法都是训练词嵌入的方法吗?如果是,那么我们如何同时使用两者?
我想实现的手套算法在pytorch.这是我第一次使用pytorch,我认为我的实施可能效率不高.除了显而易见的(for loop每个批次运行的矢量化)有什么能让我加快速度吗?我发现它self.optimizer.step()特别贵.
from torch.autograd import Variable
import numpy as np
import torch
import torch.optim as optim
import torch.nn as nn
from scipy import sparse
from collections import Counter
import gensim.utils as utils
import pandas as pd
from collections import deque
import time
import gensim.utils as utils
def tokenize_sentences(sentences,enforce_lower = True):
return [list(utils.tokenize(sentence,lowercase=enforce_lower)) for sentence in sentences]
class GloVe(nn.Module):
def __init__(self, window = 3, size = 100, xmax = 2, alpha …Run Code Online (Sandbox Code Playgroud) 我正在使用GloVe作为研究的一部分。我已经从这里下载了模型。我一直在用GloVe进行句子分类。一些STEM主题说,我正在分类的句子是特定于特定领域的。但是,由于现有的GloVe模型是在通用语料库上训练的,因此对于我的特定任务,它们可能无法产生最佳结果。
所以我的问题是,我将如何加载经过重新训练的模型,然后在自己的语料库上再对其进行一点再训练,以学习语料库的语义呢?如果可能的话,这样做是有好处的。
我想使用预训练的 GloVe 嵌入作为 RNN 编码器/解码器中嵌入层的初始权重。代码在 Tensorflow 2.0 中。简单地将嵌入矩阵作为 weights = [embedding_matrix] 参数添加到 tf.keras.layers.Embedding 层不会这样做,因为编码器是一个对象,我现在不确定在训练时间。
我的代码严格遵循Tensorflow 2.0 文档中的神经机器翻译示例。在此示例中,我将如何向编码器添加预先训练的嵌入矩阵?编码器是一个对象。当我开始训练时,GloVe 嵌入矩阵对 Tensorflow 图不可用。我收到错误消息:
运行时错误:无法在 Tensorflow 图形函数中获取值。
代码在训练过程中使用了 GradientTape 方法和教师强制。
我尝试修改编码器对象以在各个点包含 embedding_matrix,包括在编码器的init、 call 和 initialize_hidden_state 中。所有这些都失败了。stackoverflow 和其他地方的其他问题是针对 Keras 或更旧版本的 Tensorflow,而不是 Tensorflow 2.0。
class Encoder(tf.keras.Model):
def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz):
super(Encoder, self).__init__()
self.batch_sz = batch_sz
self.enc_units = enc_units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim, weights=[embedding_matrix])
self.gru = tf.keras.layers.GRU(self.enc_units,
return_sequences=True,
return_state=True,
recurrent_initializer='glorot_uniform')
def call(self, x, hidden):
x = self.embedding(x)
output, state …Run Code Online (Sandbox Code Playgroud) 我是 Keras 新手。
\n\n我的目标是创建用于推文情感分析的神经网络多分类。
\n\n我Sequential用来Keras构建我的模型。
我想在模型的第一层使用预先训练的词嵌入gloVe,特别是.
这是我目前的模型:
\n\nmodel = Sequential()\nmodel.add(Embedding(vocab_size, 300, weights=[embedding_matrix], input_length=max_length, trainable=False))\nmodel.add(LSTM(100, stateful=False))\nmodel.add(Dense(8, input_dim=4, activation='relu'))\nmodel.add(Dense(3, activation='softmax'))\nRun Code Online (Sandbox Code Playgroud)\n\nembedding_matrix由来自文件的向量填充glove.840B.300d.txt
由于我对神经网络模型的输入是句子(或推文),并且在查阅了一些理论之后,我希望对于嵌入层之后的层,在获取推文中的每个词向量之后,对句子\xe2\x80\x99s进行平均词向量。
\n\n目前我使用的是LSTM,我想用平均技术或这种技术来代替它p-means。我在文档中找不到这个keras。
我不确定这是问这个问题的正确地方,但我们将不胜感激所有帮助。
\n我已经使用 keras 来使用预训练的词嵌入,但我不太确定如何在 scikit-learn 模型上做到这一点。
我也需要在 sklearn 中执行此操作,因为我正在使用vecstack集成 keras 顺序模型和 sklearn 模型。
这就是我为 keras 模型所做的:
glove_dir = '/home/Documents/Glove'
embeddings_index = {}
f = open(os.path.join(glove_dir, 'glove.6B.200d.txt'), 'r', encoding='utf-8')
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
f.close()
embedding_dim = 200
embedding_matrix = np.zeros((max_words, embedding_dim))
for word, i in word_index.items():
if i < max_words:
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
embedding_matrix[i] = embedding_vector
model = Sequential()
model.add(Embedding(max_words, embedding_dim, input_length=maxlen)) …Run Code Online (Sandbox Code Playgroud) 在NLP任务中使用GloVe嵌入时,GloVe中可能不存在来自数据集的某些单词。因此,我们为这些未知单词实例化随机权重。
是否可以冻结从GloVe获得的重量,并仅训练新实例化的重量?
我只知道我们可以设置:model.embedding.weight.requires_grad = False
但这使新单词难以训练。
还是有更好的方法来提取单词的语义。
当我执行以下操作时:
>>> import gensim.downloader as api
>>> model = api.load("glove-twitter-25") # load glove vectors
Run Code Online (Sandbox Code Playgroud)
gensim.downloader API 抛出以下错误:
[Errno 2] 没有这样的文件或目录:“/Users/vtim/gensim-data/information.json”。
我究竟做错了什么?
虽然迁移学习/微调最近的语言模型,例如 BERT 和 XLNET,是迄今为止非常普遍的做法,但对于 GloVe 来说如何?
基本上,在使用 GloVe 来获得下游神经网络可以使用的密集向量表示时,我看到了两个选项。
1) 微调 GloVe 嵌入(在 pytorch 术语中,启用梯度)
2)只使用没有梯度的嵌入。
例如,给定 GloVe 的嵌入矩阵,我做
embed = nn.Embedding.from_pretrained(torch.tensor(embedding_matrix, dtype=torch.float))
...
dense = nn.Linear(...)
Run Code Online (Sandbox Code Playgroud)
仅使用 GloVe 来获得向量表示(并且只训练密集层和潜在的其他层)是最佳实践,还是也可以微调嵌入矩阵?
我正在使用 GloVe 方法进行预训练的词向量。数据包含维基百科数据上的向量。嵌入数据时,我收到错误消息,指出无法将字符串转换为浮点数:'ng'
我尝试浏览数据,但找不到符号“ng”
# load embedding as a dict
def load_embedding(filename):
# load embedding into memory, skip first line
file = open(filename,'r', errors = 'ignore')
# create a map of words to vectors
embedding = dict()
for line in file:
parts = line.split()
# key is string word, value is numpy array for vector
embedding[parts[0]] = np.array(parts[1:], dtype='float32')
file.close()
return embedding
Run Code Online (Sandbox Code Playgroud)
这是错误报告。请进一步指导我。
runfile('C:/Users/AKSHAY/Desktop/NLP/Pre-trained GloVe.py', wdir='C:/Users/AKSHAY/Desktop/NLP')
C:\Users\AKSHAY\AppData\Local\conda\conda\envs\py355\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is …Run Code Online (Sandbox Code Playgroud) glove ×13
nlp ×6
python ×5
pytorch ×3
tensorflow ×3
word2vec ×3
gensim ×2
keras ×2
apache-beam ×1
dataset ×1
download ×1
embedding ×1
python-3.x ×1
scikit-learn ×1
stanford-nlp ×1