【问题标题】:Saving a sequence of 3rd-order Tensors and reading it back without losing array format保存一系列 3 阶张量并在不丢失数组格式的情况下将其读回
【发布时间】:2019-09-12 15:30:16
【问题描述】:

Python 3.7,Numpy:我需要保存一个使用 numpy 创建的三阶对象。准确地说,它是一个数组列表。数组在加载后使用 numpy.dot() 矩阵乘以向量。有没有办法在不丢失格式的情况下保存这个对象(例如在 .txt 文件中)?

如果我只是使用 .write() 将对象放入 .txt 文件中,我会将其转换为字符串。我当然可以将其转换回浮点数组,但在此之前,我想知道是否有更简单或更有效的方法。

看起来像这样:

    BigObject = []
    for i in (0, Size1):
        BigObject.append(np.random.uniform(-1, 1, (Size2, Size3)))

    with open("test.txt", "w+") as output:
        output.write(str(BigObject))

我如何保存它和

    with open("test.txt", "r") as input:
        NewBigObject = input.read()

我是怎么读的。

这确实给了我一个 NewBigObject 的字符串,我不能将它矩阵乘以一个向量。

BigArray 的保存方式无关紧要。我只想知道是否有一种聪明的方法可以在不丢失格式的情况下保存它。现在我可以运行一系列split()float() 命令来取回原始对象。但是我可以更快或更优雅地做到这一点吗?

【问题讨论】:

    标签: python numpy serialization deserialization


    【解决方案1】:

    这是一种将数组保存为 dict 但不保存为 list 的方法(因为将其保存为列表会将所有数组连接到一个单独的数组中,这是我们不想要的),然后将其加载回来以供阅读丢失数组格式。

    # sample array to work with
    In [76]: arr = np.arange(12).reshape(4, 3)
    
    # make a dict of say 4 copies of the array
    In [77]: dict_of_arrs = {idx: arr for idx in range(4)}
    
    # serialize it to disk; will be saved as `serialized_arrays.npy`
    In [78]: np.save('serialized_arrays', dict_of_arrs)
    
    # load it back for reading/processing
    In [79]: loaded_arrs = np.load('serialized_arrays.npy')
    
    # flatten it out and just take the 0th element in the list.
    In [80]: loaded_arrs.ravel()[0]
    Out[80]: 
    {0: array([[ 0,  1,  2],
            [ 3,  4,  5],
            [ 6,  7,  8],
            [ 9, 10, 11]]), 1: array([[ 0,  1,  2],
            [ 3,  4,  5],
            [ 6,  7,  8],
            [ 9, 10, 11]]), 2: array([[ 0,  1,  2],
            [ 3,  4,  5],
            [ 6,  7,  8],
            [ 9, 10, 11]]), 3: array([[ 0,  1,  2],
            [ 3,  4,  5],
            [ 6,  7,  8],
            [ 9, 10, 11]])}
    

    上面会返回一个dict;然后,您可以遍历此 dict 并访问数组。如果您愿意,可以在制作 dict dict_of_arrs 时提供一些合理的键。

    【讨论】:

    • serialized_arrays.npy是程序文件夹中的一个文件,完美。非常感谢,帮了大忙!
    • 更新:所以我现在又回到了这个问题上,似乎loaded_arrs = np.load('serialized_arrays.npy') 造成了一些麻烦。我用loaded_arrs = np.load('serialized_arrays.npy', allow_pickle=True) 修复了它。现在我希望我不会因此而毁了任何东西。
    猜你喜欢
    • 2021-08-27
    • 2020-12-02
    • 2015-12-22
    • 1970-01-01
    • 2011-01-14
    • 2013-02-16
    • 2017-01-01
    • 2016-06-19
    • 1970-01-01
    相关资源
    最近更新 更多