pytorch中的可学习查找表实现之nn.Embedding

假设我们需要一个查找表(Lookup Table),我们可以根据索引数字快速定位查找表中某个具体位置并读取出来。最简单的方法,可以通过一个二维数组或者二维list来实现。但如果我希望查找表的值可以通过梯度反向传播来修改,那么就需要用到nn.Embedding来实现了。

其实,我们需要用反向传播来修正表值的场景还是很多的,比如我们想存储数据的通用特征时,这个通用特征就可以用nn.Embedding来表示,常见于现在的各种codebook的trick。闲话不多说,我们来看栗子:

python 复制代码
import torch
from torch import nn

table = nn.Embedding(10, 3)
print(table.weight)
idx = torch.LongTensor([[1]])
b = table(idx)
print(b)

'''
output
Parameter containing:
tensor([[-0.2317, -0.9679, -1.9324],
        [ 0.2473,  1.1043, -0.7218],
        [ 0.5425, -0.3109, -0.1330],
        [-1.4006, -0.0675,  0.1376],
        [-0.1995,  0.7168,  0.5692],
        [-1.3572, -0.6407, -0.0128],
        [-0.0773,  1.1928, -1.0836],
        [ 0.1721, -0.9232, -0.4059],
        [ 1.6108, -0.4640,  0.3535],
        [ 0.6975,  1.6554, -0.2217]], requires_grad=True)
tensor([[[ 0.2473,  1.1043, -0.7218]]], grad_fn=<EmbeddingBackward0>)
'''

这段代码实际上就实现了一个查找表的功能,索引值为\[1](注意有两个中括弧),返回值为对应的表值。我们还可以批量查找表值:

python 复制代码
import torch
from torch import nn

table = nn.Embedding(10, 3)
print(table)
print(table.weight)

indices = torch.LongTensor([[1,2,4,5],[4,3,2,9]])
print(indices)

out = table(indices)
print(out)
print(out.shape)

通过输入索引张量来获取表值:2,4 -> 2,4,3,请注意这个shape变化,即对应位置的索引获得对应位置的表值。

参考:https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html

本人亲自整理,有问题可留言交流~

相关推荐
承渊政道1 天前
【从零开始大模型开发与微调:基于PyTorch与ChatGLM】(从ChatGLM本地化到LoRA、PEFT的高级微调)
android·人工智能·pytorch·chatglm·本地化部署·大模型开发与微调
Smoothcloud润云2 天前
GPU算力平台推荐:新手租GPU时,镜像环境和显存应该怎么选?
大数据·人工智能·pytorch·分布式·深度学习·gpu算力
田里的水稻2 天前
PyTorch_TensorBoard展示
人工智能·pytorch·python·深度学习·神经网络
想七想八不如114082 天前
元学习简单入门
人工智能·pytorch·python·深度学习·学习·机器学习
田里的水稻3 天前
PyTorch_torchvision---数据集下载\TensorBoard可视化
人工智能·pytorch·python·深度学习·机器学习
智恒百亿3 天前
5090 八卡服务器踩坑实录:架构、多卡通信、PyTorch Distributed 一次说清楚
服务器·pytorch·架构
田里的水稻3 天前
PyTorch-Dataset\DataLoader数据加载
人工智能·pytorch·python
智码看视界3 天前
深度学习:环境搭建PyTorch vs TensorFlow 选型
pytorch·深度学习·tensorflow·gpu·环境搭建·cuda·框架选型
论文复现现场3 天前
InfiniteTalk 需要多少显存?RTX 3090 24GB 单卡如何验证 480P、排查 OOM
pytorch·模型部署·ai视频生成·显存优化·infinitetalk·rtx3090·cuda oom
Zip-List3 天前
工作小记-pytorch的算子优化: 转gpu核函数 python调c
c语言·c++·pytorch·python·cuda