完美解决RuntimeError: view size is not compatible with input tensor‘s size and stride.

RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(…) instead.

报错在这一句:

correct_k = correct[:k].view(-1).float().sum(0)

加入.contiguous()即可,修改如下:

correct_k = correct[:k].contiguous().view(-1).float().sum(0)

这是因为view()需要Tensor中的元素地址是连续的,因为可能出现Tensor不连续的情况。

修改方法为:在.view前加.contiguous(),使其变为连续就ok。

最终效果如下:


参考链接:

一步真实解决RuntimeError: view size is not compatible with input tensor‘s size and stride-pudn.com

猜你喜欢

转载自blog.csdn.net/weixin_43570470/article/details/126648404