本文最后更新于:2023年12月5日 下午

在训练 Pytorch 网络时遇到错误 At least one stride in the given numpy array is negative, and tensors with negative strides are not currently supported., 本文记录原因与解决方案。

问题复现

  • 在numpy 图像数据转为 torch.tensor 之前使用 numpy 执行内部形变的操作,常见的有:

    • 通道转换

      1
      image = image[:,:,::-1]
    • 图像翻转

      1
      2
      3
      image = np.fliplr(image)
      # or
      image = np.flipud(image)
  • 此类操作之后经过 Pytorch 的 Dataloader,读取tensor 时会报错

1
ValueError: At least one stride in the given numpy array is negative, and tensors with negative strides are not currently supported. (You can probably work around this by making a copy of your array with array.copy().)

问题原因

  • 输入网络的 Tensor 需要是内存连续
  • 但是 numpy 上述变换后为了速度考虑不会改变数据内存,这就导致拿到的数据在内存中不连续,导致错误

解决方案

  • 可以按照报错中建议的方式
1
image = image.copy()
  • 也可以正经解决 numpy 内存连续的问题
1
image = np.ascontiguousarray(image)

参考资料



文章链接:
https://www.zywvvd.com/notes/study/deep-learning/bug-fix/numpy-negative/numpy-negative/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

错误 At least one stride in the given numpy array is negative, and tensors with negative strides are not currently supported. 解决方案
https://www.zywvvd.com/notes/study/deep-learning/bug-fix/numpy-negative/numpy-negative/
作者
Yiwei Zhang
发布于
2022年3月4日
许可协议