在我的前向方法中,我目前有一个大小为 torch.Size([8,22,16]) 的字符嵌入,其中 8 表示批量大小,22 表示数据集中每个单词的最大字符长度,16 是隐藏的维度。我还为每个单词的字符设置了一个掩码,表示该字符是否有效,其大小为 torch.Size([8,22])。我尝试使用 unsqueeze() 和 view() 无济于事。
我不断收到这样的错误:
RuntimeError: The size of tensor a (16) must match the size of tensor b (22) at non-singleton dimension 3
这就是我的网络的样子:
class Network(nn.Module):
def __init__(self, embedding_dim, hidden_dim, n_outputs):
self.embedding = nn.Embedding(256, embedding_dim)
self.linear1 = nn.Linear(embedding_dim, hidden_dim)
self.linear2 = nn.Linear(hidden_dim, n_outputs)
def forward(self, chars, mask):
chars_embeddings = self.embedding(chars)
chars_embeddings = torch.mul(chars_embeddings, mask.unsqueeze(2))
pool_embeddings = chars_embeddings.mean(dim=1)
lin_out = self.linear1(pool_embeddings)
drop_out = F.dropout(F.relu(lin_out), training=self.training)
out = self.linear2(dropout)
return out
我尝试了不同的解压和查看操作,但没有成功。
从错误
non-singleton dimension 3
判断,您的尺寸似乎比您指定的要多,如果尺寸符合您的指定,则应该是non-singleton dimension 2
。将 mask.unsqueeze(2)
更改为 mask.unsqueeze(3)
可能会解决该问题。