【问题标题】:Dimension out of range when applying l2 normalization in Pytorch在 Pytorch 中应用 l2 归一化时尺寸超出范围
【发布时间】:2018-12-23 05:37:36
【问题描述】:

我收到运行时错误:

RuntimeError: Dimension out of range (expected 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

我将不胜感激。 谢谢

【问题讨论】:

    标签: python normalization pytorch dimensions outofrangeexception


    【解决方案1】:

    我建议检查i_batch 的形状(例如print(i_batch.shape)),因为我怀疑i_batch 只有一维(例如形状[N])。

    这可以解释为什么 PyTorch 抱怨您只能在维度 #0 上进行归一化;当您要求在维度 #1 (c.f. dim=1) 上完成操作时。

    【讨论】:

    • 感谢您的建议 :)。你是对的,我在预处理相当于 {i_batch} 的数据时遗漏了一些数据。刚刚修好了。
    猜你喜欢
    • 2021-09-13
    • 2021-08-26
    • 1970-01-01
    • 2021-10-02
    • 2018-06-30
    • 2021-12-15
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    相关资源
    最近更新 更多