Pytorch nn.Embedding用法(包括加载预训练模型,加载Word2vec,加载glove)

pytorch nn.Embedding

class torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2, scale_grad_by_freq=False, sparse=False)

  • num_embeddings (int) - 嵌入字典的大小

  • embedding_dim (int) - 每个嵌入向量的大小

  • padding_idx (int, optional) - 如果提供的话,输出遇到此下标时用零填充

  • max_norm (float, optional) - 如果提供的话,会重新归一化词嵌入,使它们的范数小于提供的值

  • norm_type (float, optional) - 对于max_norm选项计算p范数时的p

  • scale_grad_by_freq (boolean, optional) - 如果提供的话,会根据字典中单词频率缩放梯度

  • weight weight (Tensor) -形状为(num_embeddings, embedding_dim)的模块中可学习的权值

    输入: LongTensor (N, W), N = mini-batch, W = 每个mini-batch中提取的下标数
    输出: (N, W, embedding_dim)


加载预训练模型

self.embed = nn.Embedding(vocab_size, embedding_dim)
self.embed.weight.data.copy_(torch.from_numpy(pretrained_embeddings))


embed = nn.Embedding.from_pretrained(feat)

加载glove

先将glove向量转换成Word2vec向量。然后使用gensim库导入。

'''转换向量过程'''
from gensim.test.utils import datapath, get_tmpfile
from gensim.models import KeyedVectors
# 已有的glove词向量
glove_file = datapath('test_glove.txt')
# 指定转化为word2vec格式后文件的位置
tmp_file = get_tmpfile("test_word2vec.txt")
from gensim.scripts.glove2word2vec import glove2word2vec
glove2word2vec(glove_file, tmp_file)

‘’‘’导入向量‘’‘’
# 加载转化后的文件
wvmodel = KeyedVectors.load_word2vec_format(tmp_file)
# 使用gensim载入word2vec词向量

vocab_size = len(vocab) + 1
embed_size = 100
weight = torch.zeros(vocab_size+1, embed_size)

for i in range(len(wvmodel.index2word)):
    try:
        index = word_to_idx[wvmodel.index2word[i]]
    except:
        continue
    weight[index, :] = torch.from_numpy(wvmodel.get_vector(
        idx_to_word[word_to_idx[wvmodel.index2word[i]]]))



#embed
embedding = nn.Embedding.from_pretrained(weight)






  • 26
    点赞
  • 111
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
PyTorch 中,可以使用预训练的词向量作为初始化参数来初始化 `nn.Embedding`。具体步骤如下: 1. 下载预训练的词向量文件,比如 GloVeWord2Vec 等。 2. 加载词向量文件,将每个词和其对应的向量存储到一个字典中。 3. 创建一个 `nn.Embedding` 模块,将其权重初始化为预训练的词向量。 4. 将这个 `nn.Embedding` 模块作为神经网络的一部分,用于将输入的词转换为对应的词向量。 下面是一个示例代码: ```python import torch.nn as nn import torch # 加载预训练的词向量文件 word_vectors = {} with open('path/to/word_vectors.txt', 'r', encoding='utf-8') as f: for line in f: word, vector = line.split(' ', 1) word_vectors[word] = torch.from_numpy(np.array(vector.split(), dtype='float32')) # 创建 nn.Embedding 模块,并将其权重初始化为预训练的词向量 embedding = nn.Embedding(num_embeddings=len(word_vectors.keys()), embedding_dim=len(word_vectors['the'])) weights = torch.zeros(len(word_vectors.keys()), len(word_vectors['the'])) for i, word in enumerate(word_vectors.keys()): weights[i] = word_vectors[word] embedding.weight.data.copy_(weights) # 将 nn.Embedding 模块作为神经网络的一部分,用于将输入的词转换为对应的词向量 class MyModel(nn.Module): def __init__(self, vocab_size, embedding_dim): super(MyModel, self).__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim) self.fc = nn.Linear(embedding_dim, 1) def forward(self, x): x = self.embedding(x) x = x.mean(dim=1) x = self.fc(x) return x model = MyModel(len(word_vectors.keys()), len(word_vectors['the'])) ``` 这里的 `word_vectors.txt` 文件是预训练的词向量文件,每一行表示一个词及其对应的向量,用空格分隔。`embedding_dim` 参数表示词向量的维度。在这个示例中,我们创建了一个简单的神经网络模型,其中输入为一个词的索引,输出为一个标量。在模型中,我们使用了预训练的词向量来初始化 `nn.Embedding` 模块,并将其作为模型的第一,用于将输入的词转换为对应的词向量。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值