Hi, when I use numpy.flip() on my array and then i try to create from this array torch tensor with torch.from_numpy(x)
It says
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().)
Why is this happening ? I see there are some solutions on internet but this never happened to me yet and I was using numpy.flip() a lot.
When I use min() max() on this array there is no negative number so why is this happening ?
example code:
Just normal numpy array, flip it and it crashes.
Not the values in the array/tensor are negative but the strides, which are used to access elements in the tensor via indexing.
Negative strides are not supported in PyTorch, so you would have to create a copy first:
x = torch.randn(10, 10)
x[:, ::-1]
# > ValueError: step must be greater than zero
x.numpy()[:, ::-1] # works
a = np.random.randn(10, 10)
a.strides
# > (80, 8)
a = np.flip(a)
a.strides
# > (-80, -8)
x = torch.from_numpy(a)
# > 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().)
x = torch.from_numpy(a.copy()) # works
x.stride()
# > (10, 1)
for what it’s worth, this error can happen if you’re trying to make a tensor out of an image that has been “rotated” via metadata adjustment.
for example:
in macOS, select an image and push CMD+L. this doesn’t rewrite any raster data, it just changes the orientation of the image in the image’s metadata.
load the image into a python script via imageio: import imageio; image = imageio.imread("/path/to/image.jpg") — imageio respects the image’s metadata and implements the rotation using a negative stride in the appropriate place
try to make the image into a tensor: import torch; tensor = torch.Tensor(image)
this should raise the negative stride error.
if you write the image to disk and try the above procedure again, everything should be fine.
I meant more that with this syntax, you can extract the same values as that you would get by using a negative strides, however the order of the values is reversed now: