如何确定.npz文件的shape/size
How to determine the shape/size of .npz file
我有一个扩展名为 .npz 的文件。我怎样才能确定它的形状。
我用这段代码将它加载到 colab 上
import numpy as np
file=np.load(path/to/.npz)
我无法确定它的形状
生成样本.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")))
调用上面的函数,returns下面的输出
[('arr_0', (10,), dtype('int64')), ('arr_1', (10,), dtype('float64'))]
您可以简单地遍历每个元素并查询其形状和其他信息。
# 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,)
我有一个扩展名为 .npz 的文件。我怎样才能确定它的形状。 我用这段代码将它加载到 colab 上
import numpy as np
file=np.load(path/to/.npz)
我无法确定它的形状
生成样本.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")))
调用上面的函数,returns下面的输出
[('arr_0', (10,), dtype('int64')), ('arr_1', (10,), dtype('float64'))]
您可以简单地遍历每个元素并查询其形状和其他信息。
# 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,)