Skip to main content
 首页 » 编程设计

python之Python 中的 numpy.save( ) 和 joblib.dump( ) 有什么区别

2024年10月25日13daizhj

我在 Python 中保存了很多离线模型/矩阵/数组,并遇到了这些函数。有人能帮我列出 numpy.save( ) 和 joblib.dump( ) 的优缺点吗?

请您参考如下方法:

下面是 joblib 中的关键代码部分,应该可以说明一些问题。

def _write_array(self, array, filename): 
    if not self.compress: 
        self.np.save(filename, array) 
        container = NDArrayWrapper(os.path.basename(filename), 
                                   type(array)) 
    else: 
        filename += '.z' 
        # Efficient compressed storage: 
        # The meta data is stored in the container, and the core 
        # numerics in a z-file 
        _, init_args, state = array.__reduce__() 
        # the last entry of 'state' is the data itself 
        zfile = open(filename, 'wb') 
        write_zfile(zfile, state[-1], 
                            compress=self.compress) 
        zfile.close() 
        state = state[:-1] 
        container = ZNDArrayWrapper(os.path.basename(filename), 
                                        init_args, state) 
    return container, filename 

基本上,joblib.dump 可以选择压缩一个数组,它可以使用 numpy.save 将其存储到磁盘,或者(用于压缩)存储一个 zip 文件。此外,joblib.dump 存储一个 NDArrayWrapper(或用于压缩的 ZNDArrayWrapper),这是一个轻量级对象,用于存储保存/压缩的名称包含数组内容和数组子类的文件。