【问题标题】:How to determine the shape/size of .npz file如何确定 .npz 文件的形状/大小
【发布时间】:2021-09-14 08:55:25
【问题描述】:

我有一个扩展名为 .npz 的文件。我怎样才能确定它的形状。 我用这段代码在 colab 上加载了它

import numpy as np 
file=np.load(path/to/.npz)

我无法确定它的形状

【问题讨论】:

  • 您阅读过savez 文档吗?您的file 没有shape。这是一个dict 对象(带有keys),用于访问zip 存档中的数组。
  • 通常我们加载npy数组,并检查它们的形状。
  • 我的文件是一个图像特征文件。它通过下面给出的答案起作用。谢谢

标签: python numpy size google-colaboratory shapes


【解决方案1】:

生成样本.npz文件

import numpy as np
import zipfile


x = np.arange(10)
y = np.sin(x)

np.savez("out.npz", x, y)
def npz_headers(npz):
    """
    Takes a path to an .npz file, which is a Zip archive of .npy files.
    Generates a sequence of (name, shape, np.dtype).
    """
    with zipfile.ZipFile(npz) as archive:
        for name in archive.namelist():
            if not name.endswith('.npy'):
                continue

            npy = archive.open(name)
            version = np.lib.format.read_magic(npy)
            shape, fortran, dtype = np.lib.format._read_array_header(npy, version)
            yield name[:-4], shape, dtype

print(list(npz_headers("out.npz")))

调用上面的函数,它会返回下面的输出

[('arr_0', (10,), dtype('int64')), ('arr_1', (10,), dtype('float64'))]

【讨论】:

  • 当我调用这个函数时,它不显示任何东西 "npz_headers(path/to/.npz)" 即使在使用打印命令它显示 " "
  • 你应该解释发生了什么。我怀疑 OP 太新了,无法理解该代码的来源,以及它与实际加载数组的关系。
  • 使用“list”调用函数有效。谢谢@Pluviophile
  • 很高兴,这有帮助
【解决方案2】:

您可以简单地遍历每个元素并查询其形状和其他信息。

# create your file
d = np.arange(10)
e = np.arange(20)
np.savez("mat",x = d, y = e)

#load it
data = np.load("mat.npz")

for key in data.keys():
    print("variable name:", key          , end="  ")
    print("type: "+ str(data[key].dtype) , end="  ")
    print("shape:"+ str(data[key].shape))

输出:

variable name: x  type: int32  shape:(10,)
variable name: y  type: int32  shape:(20,)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 2010-09-05
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多