【问题标题】:Reshape multi-temporal, mutlispectral 3D numpy arrays重塑多时间、多光谱 3D numpy 数组
【发布时间】:2022-01-14 14:53:15
【问题描述】:

我正在处理多时相、多光谱的卫星图像。数据以 ((n_bands x n_timesteps), height, width) 的形式存储为 geotiff。我需要为 ML 模型训练重塑数组,其中图像中的每个像素都是一个“样本”。因此,训练数组的形状为(n_samples x n_timesteps x n_bands)

假设以下数组和相关变量。还假设数据集中的波段数为 12,时间步长为 4。因此,数组的第一维为 12*4 = 48。

x = np.random.rand(48, 512, 512)

width = x.shape[1]
height = x.shape[2]
n_samples = width * height

n_bands = 12
n_timesteps = x.shape[0] / n_bands

将数组x 重塑为x_reshape 以使x_reshape.shape 返回的最佳方法是:

(n_samples, n_timesteps, n_bands)

确保保持数据的正确顺序,以便x_reshape[0] 的切片是形状为(n_timesteps x n_features) 的数据集的单个“样本”?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    您可以使用numpy.reshape() 和之后的numpy.moveaxis() 来实现您想要的:

    import numpy as np
    
    x = np.random.rand(48, 512, 512)
    
    width = x.shape[1]
    height = x.shape[2]
    n_samples = width * height
    
    n_bands = 12
    n_timesteps = int(x.shape[0] / n_bands)
    
    x = np.reshape(x, (n_timesteps,n_bands,n_samples))
    x = np.moveaxis(x, -1, 0)
    

    【讨论】:

    • 谢谢,这非常接近,但给出了形状 (n_samples, n_bands, n_timesteps) 而不是 (n_samples, n_timesteps, n_bands)。我可以将最后一行 - np.moveaxis(x, -1, 0) 更改为 np.swapaxes(x, -1, 0),它给出 x.shape = (262144, 4, 12) 并假设数据正确对齐?
    • 对不起。我的错。我编辑了代码。我在 reshape 中更改了尺寸的顺序。
    猜你喜欢
    • 2016-02-10
    • 2017-08-15
    • 2017-11-11
    • 2018-03-17
    • 2017-09-18
    • 2020-04-22
    • 2016-05-22
    • 2019-07-10
    • 2021-03-21
    相关资源
    最近更新 更多