【发布时间】:2014-10-04 03:39:57
【问题描述】:
从h5py docs,我看到我可以使用数据集的astype 方法将HDF 数据集转换为另一种类型。这将返回一个上下文管理器,它会即时执行转换。
但是,我想读入存储为 uint16 的数据集,然后将其转换为 float32 类型。此后,我想从这个数据集中提取不同的切片,作为演员类型float32。文档将其用法解释为
with dataset.astype('float32'):
castdata = dataset[:]
这会导致整个数据集被读入并转换为float32,这不是我想要的。我想引用数据集,但将其转换为 float32 等效于 numpy.astype。如何创建对.astype('float32') 对象的引用,以便将其传递给另一个函数以供使用?
一个例子:
import h5py as HDF
import numpy as np
intdata = (100*np.random.random(10)).astype('uint16')
# create the HDF dataset
def get_dataset_as_float():
hf = HDF.File('data.h5', 'w')
d = hf.create_dataset('data', data=intdata)
print(d.dtype)
# uint16
with d.astype('float32'):
# This won't work since the context expires. Returns a uint16 dataset reference
return d
# this works but causes the entire dataset to be read & converted
# with d.astype('float32'):
# return d[:]
此外,似乎 astype 上下文仅在访问数据元素时才适用。这意味着
def use_data():
d = get_data_as_float()
# this is a uint16 dataset
# try to use it as a float32
with d.astype('float32'):
print(np.max(d)) # --> output is uint16
print(np.max(d[:])) # --> output is float32, but entire data is loaded
那么就没有一种 numpy 式的使用 astype 的方式吗?
【问题讨论】:
-
我不认为
np.max(d)在这里做了什么特别聪明的事情。由于d没有自己的.max()方法,np.max()会将数组读入内存并在其上调用np.core.umath.maximum.reduce(),使用d.dtype设置输出类型。np.max(d)和np.max(d[:])的时间几乎相同。 -
@ali_m 你可能是对的。我只是选择 np.max 作为查看数组上的操作是否返回 dtype 的方式。这对我的计算并不重要。我将主要提取我使用的切片。