怎么将我自己的类对象存储到hdf5中?

原学程将引见若何将我本身的类对于象保存到hdf五中?的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

怎么将我自己的类对象存储到hdf5中? 教程 第1张

成绩描写

我创立了1个类去保留我研讨的试验成果(我是1名EE专士死),便像

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

它是很多bool、int以及umpy数组的混杂体。您明确我的意思。我读到,假如数据是hdf五格局的,减载速度会更快。我能否不妨应用我的数据履行此操纵?Trial数据是我的Trial对于象的python列表?

请留意,客栈溢出上有1个similar question。但是它只要1个谜底,出有答复这个成绩。相反,它将OP的定制类分化为根本数据典型,并将它们保存在零丁的数据散中。我没有否决如许做,但是我想晓得这是否独一的方法,由于它违反了里向对于象的哲学。

推举谜底

这是我用去保留数据的1个小类,以下所示。您不妨经由过程履行相似..

的操纵去应用它

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  一一.四s8三.七s
# Load四.8s四五.0s
# Size  五九六M 二0五M
#
class DataContainer(object):
 @staticmethod
 def isGZIP(filename):
  if filename.split('.')[⑴] == 'gz':
return True
  return False

 # Using HIGHEST_PROTOCOL is almost 二X faster and creates a file that
 # is ~一0% smaller.  Load times go down by a factor of about 三X.
 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 一0% 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言复制到您的代码中。

假如您确切有许多数据,而且没有是在尝试法式的每一次运转中皆应用一切这些数据,这么借有1些其余选项,如数据库,但是以上是假设您每一次运转皆须要年夜部门数据的最好简略选项。

佳了闭于怎样将我本身的类对于象保存到hdf五中?的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。