栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pytorch torch.nn.embedding

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pytorch torch.nn.embedding

Embedding 模块作用:将词的索引转化为词对应的词向量,需要我们设置的两个参数:词汇表的大小和词嵌入的维度。 num_embeddings (int): size of the dictionary of embeddings
embedding_dim (int): the size of each embedding vector
import torch.nn as nn
import torch
embedding = nn.Embedding(10, 3)
string = 'hello world my name is tongkai moon sun dog and'
vocab = string.split()
print(len(vocab))
word_to_idx = {}
word_to_idx = {word: i for i, word in enumerate(vocab)}
print(word_to_idx)
hello_to_tensor = torch.tensor([word_to_idx['hello']], dtype=torch.long)
hello_embed = embedding(hello_to_tensor)
print(hello_embed)
from_pretrained 加载预训练好的词向量

  我们在进行具体nlp任务时,一般通过对应的Embedding层做词向量的处理,再拿词向量去进行下游的处理,比如分类啥的,但我们可以使用预训练好的词向量, 比如使用gensim训练好的word2vec词向量,会带来更优的性能。有一点需要注意的是 ,当我们将genism已经训练好的词向量作为自己初始化的词向量,我们可以设置 词向量 是否还有随下游任务进行变动这个参数默认是 将词向量冻结住。

 

import torch.nn as nn
import torch
weight = torch.tensor([[1, 2, 3], [4., 5, 6]], dtype=torch.float32)
embedding = nn.Embedding.from_pretrained(weight)
input = torch.tensor([1], dtype=torch.long)
embed = embedding(input)
print(embed)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/269841.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号