python - 将 OHE 查找表用于 pytorch RNN 的正确方法是什么?
问题描述
我目前正在尝试使用 pytorch 构建 LSTM RNN。一个输入向量表示为一个由 50 个整数组成的数组,对应于最多 50 个带有填充的标记的序列,其中每个整数对应于我的词汇表中的一个元素和 OHE 向量中 1 的索引。我想要一个嵌入层,它只使用一个查找表来对整数进行 One-hot 编码——有点像 tensorflow 的 OHE 层。
像这种“类型”的作品
import torch
import numpy as np
import torch.nn as nn
# vocab_size is the number of words in your train, val and test set
# vector_size is the dimension of the word vectors you are using
vocab_size, vector_size = 5, 5
embed = nn.Embedding(vocab_size, vector_size)
# intialize the word vectors, pretrained_weights is a
# numpy array of size (vocab_size, vector_size) and
# pretrained_weights[i] retrieves the word vector of
# i-th word in the vocabulary
pretrained_weights = np.zeros((vocab_size, vector_size))
np.fill_diagonal(pretrained_weights, 1)
tmp =torch.from_numpy(pretrained_weights)
embed.weight = nn.Parameter(tmp,requires_grad=False )
# Then turn the word index into actual word vector
vocab = {"some": 0, "words": 1}
word_indexes = torch.from_numpy(np.array([vocab[w] for w in ["some", "words"]]))
word_vectors = embed(word_indexes)
word_vectors.data.numpy()
>>>output
array([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.]])
但它非常hacky,并且不能很好地处理成批的输入向量。
在 RNN 开始时声明 OHE 嵌入层的正确方法是什么?
解决方案
您正在寻找的方法是torch.nn.functional.one_hot
. 它后来被添加到 PyTorch 中,所以当你用谷歌搜索它时很难找到它。
>>> import torch
>>> x = torch.arange(0,5)
>>> x
tensor([0, 1, 2, 3, 4])
>>> torch.nn.functional.one_hot(x)
tensor([[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]])
推荐阅读
- java - 我在 xml 文件中传递参数仍然系统将值作为 param-val-not-found
- unit-testing - 如何测试来自 go-playground/validator 的验证错误?
- javascript - 旋转标签 - 材质 UI 按钮
- docker - 使用 gocd CI/CD 运行 docker 容器
- powershell - 此代码是键盘记录器吗?它有什么作用?
- wordpress - 如何根据 wordpress 中的以下给定查询管理发布顺序并在主页上显示结果?
- vue.js - 将新查询推送到 vue-router 时导航重复
- angular - 角度 4:错误类型错误:无法在控制台中读取未定义的属性“订阅”
- javascript - React - 当 Axios 在单独的组件中调用时,setState 不会重新渲染页面
- .net-core - 处理实现通用接口的总线事件时避免动态调用