RuntimeError: view size is not compatible with input tensor‘s size and stride

该代码实现了一个深度学习模型的前向传播过程,使用Inception模块处理输入数据。通过计算输出的平均值和方差来估计不确定性,并基于此构建卷积核进行卷积操作,以更新输出。损失函数结合了不确定性与绝对误差。当将`out_m`替换为`x`时,由于变量的连续性问题导致错误,通过`.contiguous()`解决。
摘要由CSDN通过智能技术生成
    def forward(self, x):
        
        B, T, N = x.size()
        x = x.permute(0,2,1)
        print(x.shape)
        out1 = self.inception1(x)
        out2 = self.inception2(x)
        out3 = self.inception3(x)
        out4 = self.inception4(x)
        out5 = self.inception5(x)
        
        # UEB
        out_m = torch.mean(torch.stack([out1,out2,out3,out5,out4]), dim=0)
        print(out_m.shape)
        out_v = 1 - F.softmax(torch.var(torch.stack([out1,out2,out3,out5,out4]), dim=0, unbiased=False))
        uncertainty = self.conv_u(out_v)

        loss_ae = torch.mean(torch.abs(torch.stack([out1,out2,out3,out5,out4]) - out_m.unsqueeze(0).repeat(5,1,1,1)))
        loss = torch.abs(torch.sum(0.5*(torch.exp((-1)*uncertainty)) * loss_ae**2 + 0.5*uncertainty))

        
        kernel = self.linear_k((out_m * uncertainty).view(-1,T*N))
        kernel = kernel[0,:].view(-1,N,self.kernel_lenth).repeat(N,1,1)
        res = F.conv1d(out_m, kernel, padding = (self.kernel_lenth-1)//2)
        out = out_m + res

        out = out.permute(0,2,1)
        return out, loss

上述代码不会报错。

    def forward(self, x):
        
        B, T, N = x.size()
        x = x.permute(0,2,1)
        print(x.shape)
        out1 = self.inception1(x)
        out2 = self.inception2(x)
        out3 = self.inception3(x)
        out4 = self.inception4(x)
        out5 = self.inception5(x)
        
        # UEB
        out_m = torch.mean(torch.stack([out1,out2,out3,out5,out4]), dim=0)
        print(out_m.shape)
        out_v = 1 - F.softmax(torch.var(torch.stack([out1,out2,out3,out5,out4]), dim=0, unbiased=False))
        uncertainty = self.conv_u(out_v)

        loss_ae = torch.mean(torch.abs(torch.stack([out1,out2,out3,out5,out4]) - out_m.unsqueeze(0).repeat(5,1,1,1)))
        loss = torch.abs(torch.sum(0.5*(torch.exp((-1)*uncertainty)) * loss_ae**2 + 0.5*uncertainty))

        
        kernel = self.linear_k((x * uncertainty).view(-1,T*N))
        kernel = kernel[0,:].view(-1,N,self.kernel_lenth).repeat(N,1,1)
        res = F.conv1d(x, kernel, padding = (self.kernel_lenth-1)//2)
        out = x + res

        out = out.permute(0,2,1)
        return out, loss

把out_m改成x会报错。
但打印出来shape是一样的。

出现这个原因主要就是因为view()需要Tensor中的元素地址是连续的,因为可能出现Tensor不连续的情况,所以修改方法为:
在.view前加.contiguous(),使其变为连续就ok。

不知道为啥x不是连续的。

加了contiguous确实好了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值