Numpy.tile() 对切片数组的 “confusing” 轴感到困惑。

huangapple go评论53阅读模式
英文:

Numpy.tile() "confusing" axes on sliced array

问题

我有一个2D的NumPy数组,通过切片一个3D的rasterio数据集(即我检索到了第一个光栅波段)获得。现在,当我尝试将这个2D的NumPy数组切片成一个3D的数组,以便运行一些矢量化操作时,NumPy似乎将我的数组的轴解释为(1,2)(这是原始的轴标签),而不是(0,1)。

假设光栅数据集的形状是(1,20,20)。我想要检索存储在轴(1,2)上的2D数组,所以我这样切片它:

raster_band = raster_data[0,:,:]

尝试将其切片成形状为(20,20,4)的张量,像这样:

tensor = np.tile(raster_band, (1,1,4))

返回的张量形状是(1,20,80),而不是预期的结果。

我尝试过各种扁平化和挤压的方法,但都没有解决这个问题。有人知道如何巧妙地处理这种行为吗?

英文:

I have a 2D numpy array that I have retrieved by slicing a 3D rasterio data set (i.e. I retrieved the first raster band). Now, when I try to tile this 2D numpy array into a 3D array in order to run some vectorized operations, numpy seems to interpret the axes of my array as (1,2) (which were the original axis labels) instead of (0,1).

Let's assume the raster dataset has the shape (1,20,20). I want to retrieve the 2D array stored in axes (1,2), so I slice it like so:

raster_band = raster_data[0,:,:]

Trying to tile this into a tensor of the shape (20,20,4), like this:

tensor = np.tile(raster_band, (1,1,4))

returns a tensor of the shape (1,20,80) instead of the expected outcome.

I've tried variations of flatten and squeeze but nothing solved this for me. Does anyone know a smart way to handle this behaviour?

答案1

得分: 0

将其在平铺之前转为3D:

tensor = np.tile(raster_band[..., None], (1, 1, 4))

完整示例:

raster_data = np.arange(400).reshape((1, 20, 20))
raster_band = raster_data[0,:,:]
tensor = np.tile(raster_band[..., None], (1, 1, 4))
tensor.shape
# (20, 20, 4)
英文:

You need to make it 3D before tiling:

tensor = np.tile(raster_band[...,None], (1, 1, 4))

Full example:

raster_data = np.arange(400).reshape((1, 20, 20))
raster_band = raster_data[0,:,:]
tensor = np.tile(raster_band[..., None], (1, 1, 4))
tensor.shape
# (20, 20, 4)

huangapple
  • 本文由 发表于 2023年3月3日 20:29:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75627094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定