在 Pytorch 中应用 l2 归一化时尺寸超出范围
Dimension out of range when applying l2 normalization in Pytorch
我收到运行时错误:
RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1)`
并且不知道如何修复它。
错误似乎是指行:
i_enc = F.normalize(input =i_batch, p=2, dim=1, eps=1e-12) # (batch, K, feat_dim)
我正在尝试通过应用 L2 范数对图像特征(批次 x 36 x 2038)进行编码。以下是该部分的完整代码。
def forward(self, q_batch, i_batch):
# batch size = 512
# q -> 512(batch)x14(length)
# i -> 512(batch)x36(K)x2048(f_dim)
# one-hot -> glove
emb = self.embed(q_batch)
output, hn = self.gru(emb.permute(1, 0, 2))
q_enc = hn.view(-1,self.h_dim)
# image encoding with l2 norm
i_enc = F.normalize(input =i_batch, p=2, dim=1, eps=1e-12) # (batch, K, feat_dim)
q_enc_copy = q_enc.repeat(1, self.K).view(-1, self.K, self.h_dim)
q_i_concat = torch.cat((i_enc, q_enc_copy), -1)
q_i_concat = self.non_linear(q_i_concat, self.td_W, self.td_W2 )#512 x 36 x 512
i_attention = self.att_w(q_i_concat) #512x36x1
i_attention = F.softmax(i_attention.squeeze(),1)
#weighted sum
i_enc = torch.bmm(i_attention.unsqueeze(1), i_enc).squeeze() # (batch, feat_dim)
# element-wise multiplication
q = self.non_linear(q_enc, self.q_W, self.q_W2)
i = self.non_linear(i_enc, self.i_W, self.i_W2)
h = torch.mul(q, i) # (batch, hid_dim)
# output classifier
# BCE with logitsloss
score = self.c_Wo(self.non_linear(h, self.c_W, self.c_W2))
return score
如有任何帮助,我将不胜感激。
谢谢
我建议检查 i_batch
的形状(例如 print(i_batch.shape)
),因为我怀疑 i_batch
只有一维(例如形状 [N]
)。
这可以解释为什么 PyTorch 抱怨您只能在维度 #0 上进行归一化;当您要求在维度 #1 (c.f.dim=1
).
上完成操作时
我收到运行时错误:
RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1)`
并且不知道如何修复它。
错误似乎是指行:
i_enc = F.normalize(input =i_batch, p=2, dim=1, eps=1e-12) # (batch, K, feat_dim)
我正在尝试通过应用 L2 范数对图像特征(批次 x 36 x 2038)进行编码。以下是该部分的完整代码。
def forward(self, q_batch, i_batch):
# batch size = 512
# q -> 512(batch)x14(length)
# i -> 512(batch)x36(K)x2048(f_dim)
# one-hot -> glove
emb = self.embed(q_batch)
output, hn = self.gru(emb.permute(1, 0, 2))
q_enc = hn.view(-1,self.h_dim)
# image encoding with l2 norm
i_enc = F.normalize(input =i_batch, p=2, dim=1, eps=1e-12) # (batch, K, feat_dim)
q_enc_copy = q_enc.repeat(1, self.K).view(-1, self.K, self.h_dim)
q_i_concat = torch.cat((i_enc, q_enc_copy), -1)
q_i_concat = self.non_linear(q_i_concat, self.td_W, self.td_W2 )#512 x 36 x 512
i_attention = self.att_w(q_i_concat) #512x36x1
i_attention = F.softmax(i_attention.squeeze(),1)
#weighted sum
i_enc = torch.bmm(i_attention.unsqueeze(1), i_enc).squeeze() # (batch, feat_dim)
# element-wise multiplication
q = self.non_linear(q_enc, self.q_W, self.q_W2)
i = self.non_linear(i_enc, self.i_W, self.i_W2)
h = torch.mul(q, i) # (batch, hid_dim)
# output classifier
# BCE with logitsloss
score = self.c_Wo(self.non_linear(h, self.c_W, self.c_W2))
return score
如有任何帮助,我将不胜感激。 谢谢
我建议检查 i_batch
的形状(例如 print(i_batch.shape)
),因为我怀疑 i_batch
只有一维(例如形状 [N]
)。
这可以解释为什么 PyTorch 抱怨您只能在维度 #0 上进行归一化;当您要求在维度 #1 (c.f.dim=1
).