您的位置首页 >人工智能 >

PyTorch 报错 some of the strides of a given numpy array are negative数组 flip 翻转后先 c

这个报错的根源是 numpy 数组经过 flip、步长为负的切片操作之后,得到的是非连续视图(view),底层内存没有重新排布,stride(步长)出现负数;而 torch.from_numpy 不支持负步长的 numpy 数组,直接转换就抛出异常。最常见场景就是 np.flip、[::-1] 翻转数组,很多人直接把翻转后的 numpy 数组丢进 from_numpy,没有先复制,就触发报错。核心解决思路:翻转之后先调用.copy () 生成内存连续、步长为正的新数组,再交给 torch.from_numpy。

一、报错原理拆解

  • numpy 的 flip /arr [::-1] 不会拷贝数据,只是修改元信息里的 stride,生成视图
  • 负 stride 代表读取方向反向,数据和原数组共享同一块内存
  • torch.from_numpy 要求输入 numpy 数组 stride 全部为正、内存连续,不支持反向视图
  • 注意:torch.flip 不存在这个问题,只有 numpy 翻转后转 tensor 才会踩坑

二、方案对比

方案代码写法优点缺点
方案 1:flip 后.copy ()(推荐)arr = np.flip(arr).copy()改动最小,保留 numpy 预处理逻辑少量内存拷贝开销
方案 2:改用 torch.fliptensor = torch.flip(tensor, dims=[...])全程 torch,无 numpy 转换问题需要提前转 tensor,预处理逻辑迁移
方案 3:np.ascontiguousarrayarr = np.ascontiguousarray(np.flip(arr))生成连续内存,和 copy 效果接近可读性略弱于 copy

三、错误示例代码

import numpy as np

import torch

❌ flip后直接from_numpy,负stride报错

arr = np.random.rand(32,128)

arr = np.flip(arr, axis=0)

t = torch.from_numpy(arr)

四、正确写法示例

import numpy as np

import torch

✅ flip之后先copy,消除负stride

arr = np.random.rand(32,128)

arr = np.flip(arr, axis=0).copy()

t = torch.from_numpy(arr)

也可以用 ascontiguousarray:

arr = np.flip(arr, axis=0)

arr = np.ascontiguousarray(arr)

t = torch.from_numpy(arr)

五、排查清单

  1. 定位报错的 numpy 数组,检查是否经过 ::-1、flip、fancy 索引
  2. 打印数组信息确认:print(arr.flags, arr.strides),看到负 stride 就是问题点
  3. copy 之后,数组不再和原数组共享内存,修改其中一个不会互相影响
  4. 如果是图像数据,HWC 翻转、通道反转都容易出现该问题
  5. 区分:torch.flip 是 tensor 层面操作,不存在负 stride 报错,优先全链路 tensor 处理
  6. 不要尝试直接修改 stride,numpy 不支持手动设置 stride

【相关 FAQ】

问题 1:some of the strides of a given numpy array are negative,为什么 flip 之后会出现负 stride?

回答 1:some of the strides of a given numpy array are negative,np.flip 和 [::-1] 只是创建数组视图,不复制内存,通过设置反向步长实现翻转,因此 stride 变成负数,而 torch.from_numpy 不接受负步长数组。

问题 2:some of the strides of a given numpy array are negative,.copy () 和 np.ascontiguousarray 有什么区别?

回答 2:some of the strides of a given numpy array are negative,二者都可以生成连续内存、消除负 stride;copy 强制拷贝,ascontiguousarray 在已经连续时不拷贝,性能略优,日常开发直接用.copy () 更直观。

问题 3:some of the strides of a given numpy array are negative,能不能不用 numpy flip,彻底避开这个报错?

回答 3:可以,some of the strides of a given numpy array are negative 这个报错只出现在 numpy 转 tensor 环节,把数据先转成 torch tensor,再用 torch.flip 做翻转,全程不会出现负 stride 问题。

问题 4:some of the strides of a given numpy array are negative,copy 之后会不会影响原数组?

回答 4:会,some of the strides of a given numpy array are negative 场景下,.copy () 生成独立新数组,新数组和原始数组内存分离,修改其中一个不会同步到另一个。

【参考资料】

[2026-02-18](PyTorch from_numpy negative strides error)Stack Overflow

[2026-03-01](numpy flip view and stride)NumPy 官方文档

[2025-09-22](torch.from_numpy 输入约束)PyTorch 官方文档

[2026-01-04](ascontiguousarray 使用场景)NumPy 文档

【免责声明】

本文基于 PyTorch、NumPy 常规版本行为总结,该报错只发生在 numpy 视图转 tensor;图像、信号预处理流水线大量切片翻转场景容易复现,拷贝会带来少量内存开销,高性能场景可评估迁移到 torch 原生算子。