如何将我自己的类对象存储到hdf5中? [英] How to store my own class object into hdf5?

查看:0
本文介绍了如何将我自己的类对象存储到hdf5中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类来保存我研究的实验结果(我是一名EE博士生),就像

class Trial:
    def __init__(self, subID, triID):
        self.filePath = '' # file path of the folder
        self.subID = -1    # int
        self.triID = -1    # int
        self.data_A = -1   # numpy array
        self.data_B = -1   # numpy array
        ......

它是许多bool、int和umpy数组的混合体。你明白我的意思。我读到,如果数据是hdf5格式的,加载速度会更快。我是否可以使用我的数据执行此操作?Trial数据是我的Trial对象的python列表?

请注意,堆栈溢出上有一个similar question。但它只有一个答案,没有回答这个问题。相反,它将OP的定制类分解为基本数据类型,并将它们存储在单独的数据集中。我不反对这样做,但我想知道这是不是唯一的办法,因为它违背了面向对象的哲学。

推荐答案

这是我用来保存数据的一个小类,如下所示。您可以通过执行类似..

的操作来使用它
dc = DataContainer()
dc.trials = <your list of trial objects here>
dc.save('mydata.pkl')

然后加载DO..

dc = DataContainer.load('mydata.pkl')

下面是DataContainer文件:

import gzip
import cPickle as pickle

# Simple container with load and save methods.  Declare the container
# then add data to it.  Save will save any data added to the container.
# The class automatically gzips the file if it ends in .gz
#
# Notes on size and speed (using UbuntuDialog data)
#       pkl     pkl.gz
# Save  11.4s   83.7s
# Load   4.8s   45.0s
# Size  596M    205M
#
class DataContainer(object):
    @staticmethod
    def isGZIP(filename):
        if filename.split('.')[-1] == 'gz':
            return True
        return False

    # Using HIGHEST_PROTOCOL is almost 2X faster and creates a file that
    # is ~10% smaller.  Load times go down by a factor of about 3X.
    def save(self, filename='DataContainer.pkl'):
        if self.isGZIP(filename):
            f = gzip.open(filename, 'wb')
        else:
            f = open(filename, 'wb')
        pickle.dump(self, f, protocol=pickle.HIGHEST_PROTOCOL)
        f.close()

    # Note that loading to a string with pickle.loads is about 10% faster
    # but probaly comsumes a lot more memory so we'll skip that for now.
    @classmethod
    def load(cls, filename='DataContainer.pkl'):
        if cls.isGZIP(filename):
            f = gzip.open(filename, 'rb')
        else:
            f = open(filename, 'rb')
        n = pickle.load(f)
        f.close()
        return n

根据您的用例,您可以将其用作基类,如顶部所述,或者只需将ickle.ump行复制到您的代码中。

如果您确实有很多数据,并且不是在测试程序的每次运行中都使用所有这些数据,那么还有一些其他选项,如数据库,但以上是假定您每次运行都需要大部分数据的最佳简单选项。

这篇关于如何将我自己的类对象存储到hdf5中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆