词嵌入 pytorch
时间: 2023-12-11 19:33:39 浏览: 92
以下是两种PyTorch中的词嵌入方法:
1. 使用nn.Embedding类来随机初始化词向量,并根据索引将词嵌入到张量中。可以通过设置requires_grad属性来指定训练过程中词向量是否需要更新。
```python
import torch.nn as nn
import torch
# 随机初始化词向量
embedding = nn.Embedding(4, 5)
# 打印随机初始向量矩阵
print(embedding.weight)
# 根据索引词嵌入
x = torch.tensor([[1,2,3],[1,2,1]])
tensor = embedding(x)
print(tensor)
```
2. 使用nn.Embedding.from_pretrained方法来加载预训练的词向量。可以通过设置requires_grad属性来指定训练过程中词向量是否需要更新。
```python
import torch.nn as nn
import torch
# 加载训练好的词向量
weights = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.2, 0.3, 0.4, 0.5, 0.6], [0.3, 0.4, 0.5, 0.6, 0.7], [0.4, 0.5, 0.6, 0.7, 0.8]])
embedding = nn.Embedding.from_pretrained(weights)
# 设置词向量在训练过程中不更新,默认为True
embedding.weight.requires_grad = False
inputs = torch.LongTensor([[1,2],[1,3]])
print("embedding weight:", embedding.weight)
print("embedding:", embedding(inputs))
```
阅读全文
相关推荐
















