变量screen的类型是numpy.ndarray,使用如下代码想要将numpy数组转化为torch.Tensor:
screen = torch.from_numpy(screen)
运行报错:
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().)
解决方法:
①按照报错提示,复制数组
screen = torch.from_numpy(screen.copy())
②使用numpy的调整数组连续性的函数
screen = torch.from_numpy(np.ascontiguousarray(screen))
探索原因:
与numpy数组在内存中的存储方式有关系,可以参考知乎的这篇文章:从Numpy中的ascontiguousarray说起 - 知乎
从上图numpy官方文档来看,ascontiguousarray函数是将数组按照C order的方式排列(行排列)。之前使用了numpy.transpose函数对数组维度进行调整,可能打乱了数组的行排列方式,所以采用ascontiguousarray进行调整。